Web Application Development Practical5: Flask
Before Starting the Practical…
Prepare virtual environment
python3 -m venv week5flasksource week5flask/bin/activatepip install flask mysql-connector-pythoncd week5flaskmkdir staticset FLASK_ENV=developmentset FLASK_DEBUG=1Create app.py
from flask import Flaskapp = Flask(__name__)Start develop server
python -m flask run-
在 Mac/Linux 上,
set FLASK_ENV=development和set FLASK_DEBUG=1无效,请将set换成export
注:
FLASK_ENV有两个可选项:production和development
flask默认端口为5000,某些情况下可能被占用,可以在命令行输入lsof -i :5000查看占用端口的进程,用kill -9 <PID>结束对应的进程,或者使用其它不常用端口启动,如python -m flask run --port=4999- 另,还可以通过
--host=0.0.0.0使服务在局域网内可见。
Practical Session 5: Flask
Part 1: Static site
For this practical you will be learning to use the development server that is built into Flask. This is the server you will be using to produce your coursework, so please ensure you can get it to work.
- Ensure that you have Python installed on your computer. If you are working in a Brookes lab, run Python from Apps Anywhere to install it.
- Ensure that you can access Python from the command line. Open a Command Line (Command Prompt under Windows, Terminal under MacOS) and enter
pip3. This should produce a lengthy help message.
- If you get an error message, you may need to find the directory where Python is installed and add it to your system PATH.
- Under Linux or MacOS, make sure to refer to
pip3orpython3when running from the command line, as older versions of Python may be installed as well. - Under Windows 10, running
pythonorpython3from the command line may cause Windows Store to appear, even if Python is installed. This should be resolved by the steps below.
The first step is to create a Python virtual environment. This will ensure that other Python libraries and unrelated parts of the system do not interfere with the development web server.
- Create a directory to work in and change to it by entering
cdfollowed by that directory name. - If you haven’t done so before, install Python virtual environment support by typing
pip3 install virtualenv. - Create a virtual environment in your working directory by typing
virtualenv flasktest(flasktest here is the name of the virtual environment, which you can change if you want to) - cd into the virtual environment directory (
cd flasktest), then enable the virtual environment for Python by enteringscripts\activate(under Windows) orscripts/activate(under MacOS or Linux). - Confirm that running
pythonproduces a Python startup message and a>>prompt. (It will not be in a window because you are using the command line version of Python, not the IDLE editor.) Exit Python by typingquit().
The next step is to install Flask and the related tools in the virtual environment.
- While the virtual environment is enabled (see 6 above), type
pip3 install flask mysql-connector-python. This will install Flask. This may take a short time as Flask will also be downloaded. - Open
IDLEor your preferred Python editor (you can also use Notepad++, Visual Studio Code, PyCharm, etc.) and create a file calledapp.pyinside the virtual environment directory which contains the following:
from flask import Flaskapp = Flask(__name__)Note: Do not attempt to run the program from your Python editor in the way you may have done before on COMP4004. It will not work properly because it must be run from the Flask server. We will see how to do this below.
- Create a directory called
staticinside the virtual environment directory and place an.htmlfile in it. You can use any of the HTML files you created in previous practicals. If you used a CSS file together with the HTML file, place the CSS file in thestaticdirectory too. - At the command prompt, with the virtual environment active and in the virtual environment directory, type
set FLASK_ENV=developmentto enable debug mode in Flask, and thenpython -m flask runto start the Flask development server. It should produce a message ending with “Running on…” followed by a URL. - Go to your web browser and enter the URL from the “running on” message, followed by
static/and the name of the HTML file you copied into the directory in step 11. For example, if your HTML file was calledhello.html, and the “running on” message referred to http://127.0.0.1:5000/ , you would enter the URL http://127.0.0.1:5000/static/hello.html . You should see your HTML file.
Beware: Under Windows, clicking on a Command Prompt window that is already active may cause a text selection cursor (white, non-blinking box) to appear. When this appears, it also suspends the process running in the command line, which will mean that the server will stop working! If you get no response from the server, check that there is no white box in the Command Prompt window. If there is one, click on the Command Prompt window and press ESC on the keyboard to get rid of the box.
Part 2: Dynamic site
- Halt the Flask server by pressing Ctrl+C with the command prompt window selected.
- In your Python editor, add the following lines to the
app.pyfile. Do not delete the lines already there.
@app.route('/')def hello_world(): return '<html><body><p>Hello, World!</p></body></html>'- Restart the Flask server by entering
python -m flask runin the Command Prompt window. - Type the URL http://127.0.0.1:5000/ into your web browser and you should see
Hello, Worldappear in the browser window. - Modify the Flask program in
app.pyto serve your name instead ofHello, World!. You do not need to start and stop the Flask server every time; Flask should detect that you have changed the.pyfile and reload it automatically, If this does not work, halt Flask by pressing Ctrl+C with the Command Prompt selected, and then restart it with the commandpython -m flask run. - Modify your
app.pyfile so that it includes a second route,/module, which returns “Web Application Development”. Test this using the local server.
Part 3: Development
- Modify the
app.pyfile to add a third route,/dadjoke. This route should read two GET input values,thingandquestionand produce output such that the request:
http://127.0.0.1:5000/dadjoke?thing=horse&question=Why%20the%20long%20face
Should produce the output:
A horse walked into a bar.The barman said, "Why the long face?"The horse replied, "Because I'm a horse!"The words horse and Why the long face should be drawn from the thing and question parameters and should change appropriately if they have different values.
Note the following:
- The joke should be laid out by using HTML
pelements, so you will need to return those tags in the string returned by your function. - Remember that
"signs should be written using the entity"in HTML. - Note that the
?at the end of the question does not appear in the parameter (why not?).
The function will need to add it. - You will need to add
from flask import requestto the top of your Python program to have access to therequestvariable.
- Test that the function also gives an appropriate response to
http://localhost:5000/dadjoke?thing=fish&question=Why%20are%20you%20gasping
This should give the result:
A fish walked into a bar.The barman said, "Why are you gasping?"The fish replied, "Because I'm a fish!"- Modify the function to respond appropriately to the
questionparameter being missing. The requests above should give the same results, but additionally the request
http://127.0.0.1:5000/dadjoke?thing=horse
Should produce the response
A horse walked into a bar.Ouch.It was an iron bar.If thing is something other than horse, the thing that walks into the bar should be updated appropriately.
Reference Answer
from flask import Flask, request
app = Flask(__name__)if __name__ == '__main__': app.config["ENV"] = "development" app.run(debug=True, host='0.0.0.0', port=4999)
@app.route('/')def hello_world(): return '<html><body><p>Hello, Anka!</p></body></html>'
@app.route('/module')def module(): return '<html><body><p>Web Application Development</p></body></html>'
@app.route('/dadjoke')def dadjoke(): try: thing = request.args['thing'] except KeyError: return '<html><body><p>Missing "thing" query parameter.</p></body></html>' try: question = request.args['question'] except KeyError: return f""" <html> <body> <p>A {thing} walked into a bar.</p> <p>Ouch.</p> <p>It was an iron bar.</p> </body> </html>""" return f""" <html> <body> <p>A {thing} walked into a bar.</p> <p>The barman said, "{question}"</p> <p>The horse replied, "Because I'm a {thing}!"</p> </body> </html>"""支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!