I use Flask from time to time, but I often forget how to use it, so I'll make a note here.
First, install Flask. All you have to do is type the following command.
$ pip install Flask
Next, create a file that operates the server appropriately. The following is the minimum required operation.
app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "hello"
if __name__ == "__main__":
app.run(debug=True)
Then type the following command in the directory where this file exists.
$ python app.py
Now when you access http: // localhost: 5000
, it will come back with hello.
@app.route(URL, methods) This is a wrapper that lets subsequent functions run when a request comes in. Always use it when receiving a request. Each argument is URL: the route of the URL that receives the request methods: request method There are the following usages. You can also get the variables directly from the URL.
# http://localhost:5000/Works by sending a GET request to hoge
@app.route("/hoge", methods=["GET"])
def hoge():
#Processing is done here
Flask can import URL strings as data. For example, in the example below, if you send the GET method to http: // localhost: 5000 / hoge / fuga
, it will return" hello! Fuga ".
@app.route("/hoge/<text>", methods=["GET"])
def hello(text):
return "hello! " + text
app.run(host, path, debug) Here, the application is operated. Each argument is host: IP address to run the app, default localhost port: Port that can access the app, default 5000 debug: When True, debug output when the application is running
If you use these to make changes, it looks like this:
app.run(host="0.0.0.0", port=8080, debug=True)
By setting the host as above, you can access it from an external device if you know the address of the PC running this code.
When receiving json in the request, use the json module.
from flask import Flask
import json
@app.route("/", methods=["POST"])
def hoge():
req_data = json.loads(request.data)
return req_data["hoge"]
By using the json.loads function, json data is converted into a form that can be handled by python such as arrays and dictionaries.
If you want to include json in the response, use Flask's jsonify function.
from flask import Flask, jsonify
@app.route("/", methods=["GET"])
def hoge():
res_data = {"json_data": "hogehoge"}
return jsonify(res_data)
Basically, all you have to do is wrap the data in jsonify and send it.
I would appreciate it if you could let me know if there are any mistakes or missing parts. We also accept questions.
Recommended Posts