Flask (Python WebFramework )
Html Template :
from flask import request,Flask,json,render_template
app = Flask(__name__)
@app.route(“/resource”)
Def xxx(resource)
….
…..
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1234 , Debug=true)
Passing Args
#http://localhost:1234/hello?name=Luis
@app.route('/hello')
def api_hello():
if 'name' in request.args:
return 'data: ' + request.args['name']
else:
return 'Data: no data'
Any Resource
'''http://localhost:1234/any_string
@app.route("/<string:name>/")
def string_var(name):
return "string_variable: "+name
Any Resource displaying html
#http://localhost:1234/random_string
#make sure “templates” folder is created insede project with image.html
@app.route("/<string:name>/") #<int:value>
def hello(name):
return render_template('image2.html', name=name)
All Methods
''' GET/POST/PATCH/PUT/DELETE
http://localhost:1234/verb ‘’’
@app.route('/verb', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "verb: GET\n"
elif request.method == 'POST':
return "verb: POST\n"
elif request.method == 'PATCH':
return "verb: PACTH\n"
elif request.method == 'PUT':
return "verb: PUT\n"
elif request.method == 'DELETE':
return "verb: DELETE"
POST with body in REST
'''example
POST http://localhost:1234/messages
H "Content-type: application/json"
-body '{"message":"Hello Data"}'
'''
@app.route('/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + str(request.data)
elif request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json)
else:
return "returns raw data:"+request.get_data()
POST accept from Html and send to html
Note:
1. submit button in html to trigger POST
2. Save html code in Project/templates/name.html
3. Use Javascript inside html to manipulate data.
4. Data is received to flask as dictionary
5. Python data accessed in html as “{{}}”
6. “url_for” used instead of “http://localhost:8003/submit”
input_data.html
<form action="{{ url_for('submit') }}" method="post">
<textarea name="text"></textarea>
<textarea name="text2"></textarea>
<input type="submit">
</form>
output_2data.html
<p>text1 <input name="text1" type="text" value={{text1}}/></p>
<p>text2 <input name="text2" type="text" value={{text2}}/></p>
input_data2.py
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('input_data.html')
@app.route('/submit', methods=['POST'])
def submit():
data=request.form
data1=data['text']
data2=data['text2']
return render_template("output_2data.html",text1=data1,text2=data2)
#return 'You entered: {}'.format(request.form['text'])
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8003)
Error handle
@app.errorhandler(404)
def not_found(error=None):
message = { 'status': 404, 'message': 'Not Found: ' + request.url}
resp = jsonify(message)
resp.status_code = 404
return resp