一起来学习python------flask篇(一)

113 阅读2分钟

一、安装

与其他第三方库一样,直接使用pip安装,下载慢的找镜像源。

    pip install flask

二、介绍

三、搭建服务器

# 导入flask
from flask import Flask
# 创建实例
app = Flask(__name__)

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

此时执行后,控制台会输出如下信息: image.png 注意的是,此时打开网页会报404错误。因为此时网页并没有内容! image.png

四、路由

用装饰器来制定路由url,用法如下:

# 导入flask from flask import Flask 
# 创建实例 app = Flask(__name__) 

@app.route('/')
def index():
    return 'hello world!'

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

执行代码后,首页会显示index()函数返回的内容。 image.png

return的内容,也可以是html代码,就可以输入一定格式控制网页的内容,如下:

# 导入  
from flask import Flask  
  
# 创建实例  
app = Flask(__name__)  
  
@app.route('/')  
def index():  
    return 'hellow world!!!'  
  
  
@app.route('/page1')  
def page1():  
    return '<h1>hello world too!!</h1>'

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

image.png

五、Jinja2模板引擎

代码设置了/page1页面返回的内容,是html代码,加载到浏览器也会正常解析。 此时也会出现一个问题,就是html代码繁多时,再继续使用这方法就不合适了。因为,flask提供一种方法---Jinja2模板引擎

Jinja2模板引擎用法如下:

# 导入
from flask import Flask ,render_template
# 创建实例 
app = Flask(__name__) 

@app.route('/') 
def index(): 
    return 'hellow world!!!' 
    
@app.route('/page1') 
def page1(): 
    return '<h1>hello world too!!</h1>' 
    
if __name__ == '__main__': 
    app.run(port=2000,host='127.0.0.1',debug=True)

先导入了render_template。 在项目文件夹下新建一个templates文件夹,因为Jinja2模板函数会默认去templates文件夹下查找html文件。 return时要用render_template指向html文件。代码如下:

# 导入  
from flask import Flask,render_template  
  
# 创建实例  
app = Flask(__name__)  
  
@app.route('/')  
def home():  
return 'hellow world!!!'  
  
  
@app.route('/page1')  
def page1():  
return '<h1>hello world too!!</h1>'  
  
@app.route('/index')  
def index():  
return render_template('index.html')  
  
if __name__ == '__main__':  
app.run(port=2000,host='127.0.0.1',debug=True)

image.png

接下来,通过render_template方法传输数据,在html文件中显示出来。需要在render_template加入需要传输的变量,html接收方式如下: {{data}} {% python语句 %}

image.png

image.png

image.png

六、多网页跳转

一个基本的网站都是有多个页面组成的,flask框架提供给我们开发网站,必然也能数据传输、页面跳转等功能。

首先准备两个路由和函数,以及两个页面。 image.png image.png 实现网页跳转,方法有两种: 1、使用url_for image.png 2、直接使用路径 image.png

已经完成了简单的页面跳转。 看下时间,到点下班!!!后面再继续整理!