Skip to content

Instantly share code, notes, and snippets.

@dhruvilp
Last active July 13, 2019 15:06
Show Gist options
  • Save dhruvilp/28cabb65594766bb3218351edd1d922b to your computer and use it in GitHub Desktop.
Save dhruvilp/28cabb65594766bb3218351edd1d922b to your computer and use it in GitHub Desktop.
Python Guides
# Virtual Environment Setup
mkdir apis
cd apis
python3 -m venv apis
source apis/bin/activate
pip install requests
# Create a python file called test.py
import json
import requests
api_token = 'your_api_token'
api_url_base = 'https://api.digitalocean.com/v2/
headers = {'Content-Type': 'application/json','Authorization': 'Bearer {0}'.format(api_token)}
def get_account_info():
api_url = '{0}account'.format(api_url_base)
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))
else:
return None
account_info = get_account_info()
if account_info is not None:
print("Here's your info: ")
for k, v in account_info['account'].items():
print('{0}:{1}'.format(k, v))
else:
print('[!] Request Failed')
# Run python file:
python3 test.py
# POST Req:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
# Convert JSON to Python Object (Dict)
# To convert JSON to a Python dict use this:
import json
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print python_obj["name"]
print python_obj["city"]
# Convert JSON to Python Object (List)
# JSON data can be directly mapped to a Python list.
import json
array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)
for element in data['drinks']:
print element
# Convert JSON to Python Object (float)
# Floating points can be mapped using the decimal library.
import json
from decimal import Decimal
jsondata = '{"number": 1.573937639}'
x = json.loads(jsondata, parse_float=Decimal)
print x['number']
# Convert JSON to Python Object (Example)
# JSON data often holds multiple objects, an example of how to use that below:
import json
json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
try:
decoded = json.loads(json_input)
# Access data
for x in decoded['persons']:
print x['name']
except (ValueError, KeyError, TypeError):
print "JSON format error"
# Writing JSON to a file
import json
person_dict = {"name": "Bob",
"languages": ["English", "Fench"],
"married": True,
"age": 32
}
with open('person.txt', 'w') as json_file:
json.dump(person_dict, json_file)
# Pretty Print JSON
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=4, sort_keys=True))
***** OR *****
import pprint
pprint.pprint(json_data)
***** OR *****
print(json.dumps(person_dict, indent = 4, sort_keys=True))
# Reading from JSON file
import json
# read file
with open('example.json', 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
# show values
print("usd: " + str(obj['usd']))
print("eur: " + str(obj['eur']))
print("gbp: " + str(obj['gbp']))
# Iterate over JSON file
loaded_json = json.loads(json_data)
for x in loaded_json:
print("%s: %d" % (x, loaded_json[x]))
-----------------------------------------------
# FLASK
INSTALL: $ pip install Flask
# Create a file called hello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
-----------------------------------------------
API CALLS
-----------------------------------------------
from flask import json, request, jsonify, Flask
@app.route('/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json)
elif request.headers['Content-Type'] == 'application/octet-stream':
f = open('./binary', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
else:
return "415 Unsupported Media Type ;)"
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
.field-outline{
background: #fff;
padding: 10px 20px;
border-radius: 15px;
text-decoration: none;
color: #000;
position: relative;
border: 1.5px solid blue;
}
<a class="field-outline">Text1</a>
<i class="fa fa-check" style="color:green;font-size:24px"></i>
<a class="field-outline">Text2</a>
<i class="fa fa-close" style="color:red;font-size:24px"></i>
function getKeyValues(data) {
var q = [];
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = data[key];
if (value == null) {
q.push(key + "=''");
} else if (typeof value == "object") {
q.push(getKeyValues(value));
} else {
q.push(key + "=" + value);
}
}
return q.join(",");
}
function getKeyValues(d) {
return Object.keys(d).reduce((memo, key) => {
if (!d[key]) {
memo[key] = '';
} else if (typeof d[key] === 'object') {
Object.keys(d[key]).forEach((subKey) => {
memo[subKey] = d[key][subKey];
})
} else {
memo[key] = d[key];
}
return memo;
}, {})
}
Procfile: (maybe in backend)
-- web: node app.js
OR
-- web: npm start
-----------------------------------------------
#resources
* 'https://www.w3schools.com/python/python_json.asp'
* 'https://github.com/carpedm20/emoji' pip install emoji
* 'https://github.com/dominiek/python-api-skeleton'
* 'https://github.com/dominiek/python-api-skeleton/blob/master/test/utils.py'
* 'https://github.com/dhruvilp/flask_react_app'
* 'http://blog.luisrei.com/articles/flaskrest.html'
* 'http://www.findtheconversation.com/concept-map/'
* 'https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460'
* 'https://github.com/velovsky/Derived-D3.js-Collapsible-Tree'
* 'https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd'
* 'https://blockbuilder.org/tejaser/55c43b4a9febca058363a5e58edbce81'
* 'http://198.177.2.186:8088/CooCooWeb.aspx?sid=NY&train=3953'
* 'http://198.177.2.186:8088/TrainSchedule.asmx'
* 'https://github.com/alexkuz/flask-react-boilerplate'
* ag-grid: 'https://www.ag-grid.com/javascript-grid-features/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment