Python Flask - Running a simple web server
Flask is a web application framework powered by Python. It is lighter than the Django framework, and can be built from small scale servers to large scale servers, and includes Jinja and Werkzeug.
I always use Python3. Therefore, install the package using pip3 instead of pip.
In particular, Flask can be easily used for development purposes such as providing REST APIs rather than the homepage for many unspecified users.
Flask framework homepage: https://palletsprojects.com/p/flask/
Flask installation
# Install Flask $ pip3 install flask # Flask check $ flask --version
If you get the following error message:
[root@zabbix-server ~]# pip3 install flask Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by'SSLError(SSLError(1,'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c: 877)'),)': If you get an SSLError message like /packages/f2/28/2a03252dfb9ebf377f40fba6a7841b47083260bf8bd8e737b0c6952df83f/Flask-1.1.2-py2.py3-none-any.whl"$ pip3 install flask ......
[root@zabbix-server ~]#pip3 install flask --trusted-host pypi.org --trusted-host files.pythonhosted.org
Creating first Flask application
If you have Flask installed, test it using a very simple sample application.
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello Flask' @app.route('/info') def info(): return 'Info'
if __name__ == "__main__": app.run(host="192.168.126.130", port="8080")
<firstapp.py>
Run the Python code and connect to the server running Flask Web Service from your PC's web browser.
As you can see, the string'Hello Flask' specified in the Python code is successfully displayed in the web browser.
Providing various web services using flask
The following example is a collection of various examples using flasks. You can test various functions in a web browser by referring to the comment mentioned before the function.
#-*- coding: utf-8 -*- # hello.py "" Run python hello.py "" from __future__ import print_function import os from flask import Flask from flask import render_template, request,jsonify from werkzeug.utils import secure_filename UPLOAD_FOLDER ='/tmp/' app = Flask(__name__) "" Basic url connection test curl http://192.168.126.130:8080/ "" @app.route("/") def hello(): return "Hello World!" "" Basic url access test. Response using a template curl http://192.168.126.130:8080/user/ curl http://192.168.126.130:8080/user/myname "" @app.route("/user/") @app.route("/user/<username>") def user(username = None): return render_template("hello.html", name = username) "" Basic url connection parameter test (when testing, be sure to wrap the url with "". This is due to parameter &) GET method: curl "http://192.168.126.130:8080/param?user=Tom&country=USA" POST method: curl "http://192.168.126.130:8080/param" -F user=Tom -F country=USA "" @app.route("/param", methods=['GET','POST']) def param_test(): if(request.method =='POST'): user = request.form.get('user', default ='*', type = str) country = request.form.get('country', default ='*', type = str) else: user = request.args.get('user', default ='*', type = str) country = request.args.get('country', default ='*', type = str) msg ='Name:' + str(user) + 'country:'+ str(country) print(msg) return msg +'\n' "" json format data transmission by POST method curl -H "Content-Type: application/json" -X POST -d'{"name":"xyz", "address":"my address", "age":40}' http://192.168.126.130 :8080/posttest curl http://192.168.126.130:8080/posttest "" @app.route("/posttest", methods = ['GET','POST']) def posttest(): if(request.method =='POST'): some_json = request.get_json() return jsonify({'you sent': some_json}) else: return jsonify({'about':'Hello'}) "" curl http://192.168.126.130:8080/multi/10 "" @app.route("/multi/<int:num>", methods = ['GET']) def multiply10(num): return jsonify({'result': num*10}) "" Respond to the file upload form. Used by browsers. If you select and upload a file from the downloaded form, http://192.168.126.130:8080/fileupload is called. http://192.168.126.130:8080/upload "" @app.route("/upload") def upload(): return render_template('upload.html') "" curl -F "file=@./hello.py" http://192.168.126.130:8080/fileupload "" @app.route("/fileupload", methods = ['GET','POST']) def upload_file(): print ('url:', request.url) if request.method =='POST': f = request.files['file'] f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename))) return "uploads Success!" if __name__ =='__main__': app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.run(host='192.168.126.130', port="8080", debug = True)
<hello.py>
<!DOCTYPE html> <html> <body> <h1>This is the file upload page.</h1> <p> Uploading by POST method, enctype means what type of object to be delivered by post method should be encoded. </p> <p> Also, if you define the type as file in the input, it works well.</p> <p> Also, when the file is uploaded and the submit button is pressed, the url created in the action section is skipped. </p> <form action="http://192.168.126.130:8080/fileupload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" /> </form> </body> </html>
<upload.html>
<!DOCTYPE html> <html> <head> <title>Name</title> </head> <body> <H1>{{ name }}</H1> </body> </html>
<hello.html>
And the directory structure is as follows.
[root@zabbix-server pyflask]# pwd /usr/local/src/study/pyflask [root@zabbix-server pyflask]# tree . ├── firstapp.py ├── hello.py └── templates ├── hello.html └── upload.html
댓글
댓글 쓰기