时间:2023-05-25 15:15:02 | 来源:网站运营
时间:2023-05-25 15:15:02 来源:网站运营
【Python-WebApp开发】Flask 快速入门极简小案例:Flask + Django, 是目前Python WebApp 开发最主流的两个开源框架。helloworld.py
的脚本。具体可以使用 PyCharm/Jupyter/IDLE 或者记事本创建都可以。## 导入 Flaskfrom flask import Flask## 定义一个 appapp = Flask(__name__)## 路径@app.route("/")## 定义一个函数def hello_world(): ## 返回一个 HTML 语句,将显示为网页的内容 return "<p>Hello, World!</p>"
## 可以打开 ipython/Terminal/命令提示符快速运行>>> import os>>> os.getcwd()'/Users/brycewang' ## 当前工作目录
把helloworld.py
脚本复制到工作目录。$ export FLASK_APP=helloworld ## 用export 命令导入名为 helloworld 的FLASK APP$ flask run ## 用 flask命令,运行程序* Serving Flask app 'helloworld' (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://127.0.0.1:5000/ (Press CTRL+C to quit)
这里启动成功,可以到浏览器输入网址:http://127.0.0.1:5000/ 进行访问。--host=0.0.0.0
:$ flask run --host=0.0.0.0 * Serving Flask app 'helloworld' (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 all addresses. ## 对所有的 ip 地址开放 WARNING: This is a development server. Do not use it in a production deployment. * Running on http://192.168.86.164:5000/ (Press CTRL+C to quit)
## application.py## 导入 Flaskfrom flask import Flask## 定义打招呼的函数def say_hello(username = "World"): return '<p>Hello %s!</p>/n' % username## HTML 网页的主体header_text = ''' <html>/n<head> <title>EB Flask Test</title> </head>/n<body>'''instructions = ''' <p><em>Hint</em>: This is a RESTful web service! Append a username to the URL (for example: <code>/Thelonious</code>) to say hello to someone specific.</p>/n'''home_link = '<p><a href="/">Back</a></p>/n'footer_text = '</body>/n</html>'## 设置默认启用的 appapplication = Flask(__name__)## 针对现存的 URLapplication.add_url_rule('/', 'index', (lambda: header_text + say_hello() + instructions + footer_text))## URL 后面带有名字application.add_url_rule('/<username>', 'hello', (lambda username: header_text + say_hello(username) + home_link + footer_text))## 运行 appif __name__ == "__main__": ## 启用 debug 模式 ## 部署前应删除 application.debug = True application.run()
运行后,结果如下:关键词:入门