Web Application Development Practical5: Flask

1352 字
7 分钟
Web Application Development Practical5: Flask

Before Starting the Practical…#

Prepare virtual environment#

Terminal window
python3 -m venv week5flask
source week5flask/bin/activate
pip install flask mysql-connector-python
cd week5flask
mkdir static
set FLASK_ENV=development
set FLASK_DEBUG=1

Create app.py#

from flask import Flask
app = Flask(__name__)

Start develop server#

Terminal window
python -m flask run
FAQ
  • 在 Mac/Linux 上,set FLASK_ENV=developmentset FLASK_DEBUG=1 无效,请将 set 换成 export

注:FLASK_ENV 有两个可选项:productiondevelopment

  • 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.

  1. 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.
  2. 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 pip3 or python3 when running from the command line, as older versions of Python may be installed as well.
  • Under Windows 10, running python or python3 from 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.

  1. Create a directory to work in and change to it by entering cd followed by that directory name.
  2. If you haven’t done so before, install Python virtual environment support by typing pip3 install virtualenv.
  3. 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)
  4. cd into the virtual environment directory (cd flasktest), then enable the virtual environment for Python by entering scripts\activate (under Windows) or scripts/activate (under MacOS or Linux).
  5. Confirm that running python produces 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 typing quit().

The next step is to install Flask and the related tools in the virtual environment.

  1. 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.
  2. Open IDLE or your preferred Python editor (you can also use Notepad++, Visual Studio Code, PyCharm, etc.) and create a file called app.py inside the virtual environment directory which contains the following:
from flask import Flask
app = 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.

  1. Create a directory called static inside the virtual environment directory and place an .html file 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 the static directory too.
  2. At the command prompt, with the virtual environment active and in the virtual environment directory, type set FLASK_ENV=development to enable debug mode in Flask, and then python -m flask run to start the Flask development server. It should produce a message ending with “Running on…” followed by a URL.
  3. 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 called hello.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#

  1. Halt the Flask server by pressing Ctrl+C with the command prompt window selected.
  2. In your Python editor, add the following lines to the app.py file. Do not delete the lines already there.
@app.route('/')
def hello_world():
    return '<html><body><p>Hello, World!</p></body></html>'
  1. Restart the Flask server by entering python -m flask run in the Command Prompt window.
  2. Type the URL http://127.0.0.1:5000/ into your web browser and you should see Hello, World appear in the browser window.
  3. Modify the Flask program in app.py to serve your name instead of Hello, World!. You do not need to start and stop the Flask server every time; Flask should detect that you have changed the .py file 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 command python -m flask run.
  4. Modify your app.py file so that it includes a second route, /module, which returns “Web Application Development”. Test this using the local server.

Part 3: Development#

  1. Modify the app.py file to add a third route, /dadjoke. This route should read two GET input values, thing and question and 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 p elements, so you will need to return those tags in the string returned by your function.
  • Remember that " signs should be written using the entity &quot; 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 request to the top of your Python program to have access to the request variable.
  1. 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!"
  1. Modify the function to respond appropriately to the question parameter 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#

Reference Answer
app.py
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>
"""

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
Web Application Development Practical5: Flask
https://firefly.anka2.top/posts/obu/level5/semester2/wad/week5/seminar/
作者
🐦‍🔥不死鸟Anka
发布于
2026-04-08
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
A-n-k-a
Over the Frontier / Into the Front
看这里~
合作翻译官绝赞招募中!
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
59
分类
6
标签
20
总字数
550,118
运行时长
0
最后活动
0 天前

目录