importostar
Posted on June 20, 2020
You can learn web development with the Python programming language (Flask).
Flask is a python module that enables web development to be done in Python. A simple web application could be implemented with code.
If you are new to Flask, I recommend this book
Flask Hello World
The Flask module can be installed with pip. To use flask just import it in your Python app.
from flask import Flask
The program below creates the "Hello world" app in Python Flask
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello_world():
return "Hello world\n"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
You can see the following in the terminal, when running the above program,
(venv) -bash-4.2$ python3 hello_world.py
* Serving Flask app "hello_world" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
The "hello world function is added to '/' URL.
@app.route('/', methods=['GET'])
def hello_world():
The flask app starts with a run() call.
app.run(host='0.0.0.0', port=5000)
Use the app.run(debug = True) command to enable the debug option, the debugs option will be deactivated by default.
You can output anything like
You should use Python version 3 (or newer).
Routing
Routing is used to move directly from the URL to the correct Python function.
It is convenient to navigate the web sites without visiting the home page. The decorator app.route() is used for URL linking.
@app.route('/python', methods=['GET']) # decorator
def hello_python(): # bind to the method
return "Hello Python\n"
Open the url localhost:5005/python, it shows the output of hello_python().
Redirect and errors
The redirect() method returns a reply object when called and
redirects it to another location with the HTTP status code.
It has this syntax:
Flask.redirect(location, statuscode, response)
These are the regular HTTP status codes
- HTTP_300_MULTIPLE_CHOICES
- HTTP_301_MOVED_PERMANENTLY
- HTTP_302_FOUND
- HTTP_303_SEE_OTHER
- HTTP_304_NOT_MODIFIED
- HTTP_305_USE_PROXY
- HTTP_306_RESERVED
- HTTP_307_TEMPORARY_REDIRECT
The method abort() ends the session with an HTTP error.
Flask.abort(404)
You can use Flask to create all kinds of web apps, websites, to plot [1][2] and more.
Related links
Posted on June 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.