python基础flask——模板使用

364次阅读

困于心恒于虑而后作
每天学习一点点,不能放弃
今天的学习目标是:flask的模板使用
在此期间,看书学习确实有很多问题,首先是环境问题,其次就是按着书上的做但是程序运行出错,总是不知道为什么会出现这样,但终归是解决了

一、jinja2模板使用

1.首先是创建文件夹
文件夹很关键,找了很多问题,仔细检查程序,查找资料,最后发现没有文件夹,导致程序运行出错
首先在当前项目下创建文件夹templates
然后创建html文件hello.html

内容如下:

<h1>hello word!!!</h1>

创建一个带参数的html文件user.html

<h1>hello {{name}}!!!</h1>

2.创建flask服务使用模板

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/hello/<name>')
def user(name):
return render_template('user.html', name=name)
if __name__ == "__main__":
app.run(debug=True)

打开运行结果中的地址,打开后可以直接看到hello word!!!
更改地址为http://127.0.0.1:5000/hello/www
显示hello www!!!
搭建实例成功

这个实例就是展示模板的渲染,返回html文件
在user.html文件中{{name}}表示的是一个变量,告诉模板引擎渲染时添加变量的值
jinja2模板引擎支持很多种类型的变量,字典、列表和对象

二、flask-script支持命令行选项

首先还是创建hello.py文件

from flask import Flask
from flask import request
from flask_script import Manager# 这一句与原文不一致,反复查找问题才找到解决方法
app = Flask(__name__) # 声明一个Flask实例
manager=Manager(app)
@app.route('/')# 给一个路由
def browser(): # 返回request的头,返回浏览器相关信息
user_agent = request.headers.get('User-Agent')
return '<p>your browser is %s</p>' % user_agent
if __name__ == '__main__':
manager.run()# 运行

这段代码运行后不会像之前那样,出现地址可以直接访问
首先打开终端Terminal,在pycharm中可以直接进入虚拟环境,一般配置的都是虚拟环境
如果上面那段代码没有运行出错,显示没有安装,也没关系,直接pip install flask-script安装即可
安装完成之后再次运行,可以看到

usage: hello.py [-?] {shell,runserver} ...
positional arguments:
{shell,runserver}
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit

这样就没有问题了
打开终端,配置manager
执行命令,先看看帮助

python hello.py runserver --help

结果如下:

usage: hello.py runserver [-?] [-h HOST] [-p PORT] [--threaded]
[--processes PROCESSES] [--passthrough-errors] [-d]
[-D] [-r] [-R] [--ssl-crt SSL_CRT]
[--ssl-key SSL_KEY]
Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit
-h HOST, --host HOST
-p PORT, --port PORT
--threaded
--processes PROCESSES
--passthrough-errors
-d, --debug enable the Werkzeug debugger (DO NOT use in production
code)
-D, --no-debug disable the Werkzeug debugger
-r, --reload monitor Python files for changes (not 100% safe for
production use)
-R, --no-reload do not monitor Python files for changes
--ssl-crt SSL_CRT Path to ssl certificate
--ssl-key SSL_KEY Path to ssl key

执行下面的命令

python hello.py runserver --host 0.0.0.0

结果如下:

* Serving Flask app "hello" (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)

现在本机外网ip是作为web服务器可以被访问,例如本机ip为a.b.c.d,则外网可以通过http://a.b.c.d:5000/访问你的flask服务器。
暂时还没有验证,因为现在只有我一台电脑

三、bootstrap开源框架
暂时还在研究中

yiywain
版权声明:本文于2021-09-08转载自python基础flask——模板使用,共计2525字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。