Python web框架,flask学习,初次使用

Python web框架,flask学习,初次使用

首页角色扮演Project neo更新时间:2024-05-09

最近在学习Flask,这是最基本的flask使用说明。

使用前需要安装flask,命令行执行以下代码:

pip install flask

先看下简单的目录结构。主要是app.py 和index.html两个文件、

接下来介绍flask的具体使用。。。。

1、首先导入所需库,

from flask import Flask,request,render_template

2、 初始化flask对象

# 初始化Flask对象 app = Flask(__name__)

3、入口方法,浏览器不带任何路由访问,浏览器打印字符串。

# 入口方法,浏览器打印字符串 @app.route("/") def index(): return "hellow world 中国 我的"

4、最简单的接受参数,可以直接写到路由地址上,也可以通过request对象接受。

# 浏览器传参,接受参数 @app.route('/details/<id>') def details(id): type = request.args.get('type',default=1,type=int) name = '' if type == 1: name = '图书' else: name = '电脑' return "详情内容为:{},类型为:{}".format(id,name)

5、使用flask自带的末班引擎调用前段页面,并给前段页面传参

# 传参到页面, @app.route('/list') def listPage(): user = User(name='张三',age=32) goodid = request.args.get('goodid') studycontent = [ { 'type':'后端', 'project':'Ptyhhon' }, { 'type': '前段', 'project': 'ArkTS' }, { 'type': '数据库', 'project': 'neo4j' }, ] return render_template('index.html',goodid=goodid,user=user,studycontent=studycontent)

6、最后就是运行flask,配置所有ip都可以访问,端口是8000(默认5000),开启调试模式,修改代码无需重启项目就可以查看结果

if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)

完整的代码如下:

from flask import Flask,request,render_template # 初始化Flask对象 app = Flask(__name__) # 定义用户类 class User: def __init__(self,name,age): self.name = name self.age = age # 入口方法,浏览器打印字符串 @app.route("/") def index(): return "hellow world 中国 我的" # 浏览器传参,接受参数 @app.route('/details/<id>') def details(id): type = request.args.get('type',default=1,type=int) name = '' if type == 1: name = '图书' else: name = '电脑' return "详情内容为:{},类型为:{}".format(id,name) # 传参到页面, @app.route('/list') def listPage(): user = User(name='张三',age=32) goodid = request.args.get('goodid') studycontent = [ { 'type':'后端', 'project':'Ptyhhon' }, { 'type': '前段', 'project': 'ArkTS' }, { 'type': '数据库', 'project': 'neo4j' }, ] return render_template('index.html',goodid=goodid,user=user,studycontent=studycontent) if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)

7、以下是前段页面代码。主要有参数的接收,判断和循环语句的使用,

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1></h1> <h2>{{goodid}}</h2> <h3>你好!!!</h3> <h3>{{user.name}}</h3> <h3>{{user.age}}</h3> {% if user.age > 25 %} <div> 你已经成年了,应该有自己的事业</div> {% elif user.age <= 25 %} <div> 你还是个在校学生,好好学习,加油!</div> {% endif %} {% for content in studycontent %} <div> 学习类型 {{ content.type}} | 学习内容 {{ content.project}}</div> {% endfor %} </body> </html>

ok!

,
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved