Simple HTTP Server
In Python 2
python -m SimpleHTTPServer 8000
In Python 3
python3 -m http.server 8000
- In Python 2
import SimpleHTTPServer
import SocketServer
import logging
PORT = 8000
class GetHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.error(self.headers)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = GetHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()
- In Python 3
import http.server
import socketserver
import logging
PORT = 8081
class GetHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
logging.error(self.headers)
http.server.SimpleHTTPRequestHandler.do_GET(self)
Handler = GetHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
-
https://stackoverflow.com/questions/7943751/what-is-the-python-3-equivalent-of-python-m-simplehttpserver
- Update all pip versions locally
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
- https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip
Writing csv from a json object
Installation
pip3 install flatten_json
# https://github.com/amirziai/flatten
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This script read a json which is a list of dictionaries,
# then flatten this json and export as a csv file
import csv
import json
import sys
from flatten_json import flatten
def main():
import_file = sys.argv[1]
export_file = sys.argv[2]
# The import can only be a list,
# each item needs to be a dictionary
data = json.loads(open(import_file, "r").read())
if isinstance(data, list):
handled_data = []
for item in data:
handled_data.append(flatten(item))
else:
raise ValueError
if len(handled_data) == 0:
raise ValueError
schema = set()
# Add all possible schema from the list
for i in handled_data:
schema = schema.union(list(i.keys()))
print(schema)
with open(export_file, mode='w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=schema)
writer.writeheader()
for i in handled_data:
writer.writerow(i)
if __name__ == "__main__":
main()
- https://github.com/amirziai/flatten
- https://realpython.com/python-csv/#writing-csv-file-from-a-dictionary-with-csv
Useful links
- https://realpython.com/python-string-formatting/