flask 高级编程-基础

1、安装python3的虚拟环境
  which python
  /usr/local/bin/python3
  virtualenv -p /usr/local/bin/python3 env
2、查看版本
  python -V
  pip -V
3、安装flask
  pip install flask
4、常用virtual命令
  virtualenv env 创建虚拟环境
  deactivate 退出虚拟环境
  pip freeze > requirements.txt 自动生成requirements.txt文件
5、mysql安装(centos7)
  su root  # 切换到root用户
  yum -y install mysql57-community-release-el7-10.noarch.rpm # 安装mysql源
  yum -y install mysql-community-server # 安装mysql
  systemctl start mysqld.service # 启动
  systemctl status mysqld.service # 查看状态,有active (running)
  grep "password" /var/log/mysqld.log # 查找root密码
  mysql -uroot -p # 登录客户端,输入密码
  设置
    set global validate_password_policy=0;
    set global validate_password_length=1;
    ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
  exit
  yum -y remove mysql57-community-release-el7-10.noarch  # 卸载更新,因为安装了Yum Repository,以后每次yum操作都会自动更新,需要把这个卸载掉
6、mysql基础用法
  systemctl start mysqld.service # 启动
  systemctl status mysqld.service # 查看状态,有active (running)
  mysql -uroot -p # 登录
7、fisher.py
 
# -*- coding=utf-8 -*-
 
from flask import Flask
 
app = False(__name__)
 
 
@app.route('/hello')
def hello():
return 'Hello, World!'
 
 
app.run()
View Code
  
  其中,MVC中的controller就是这里面的hello函数
  python fisher.py
8、兼容两种访问方式,带/和不带/
  8.1 浏览器中输入http://127.0.0.1:5000/hello就能访问
    要想输入http://127.0.0.1:5000/hello/也能访问,@app.route('/hello')-->@app.route('/hello/')
  8.2 原理:重定向,将不带/的url重定向到了带/的url这里
    (1)浏览器访问url1地址,服务器接收到这次请求
    (2)出于某种原因(没有url所在页面或者不想让你访问url1所对应页面)
    (3)服务器会在返回的header里面增加一个标志位,location:url2,同时将返回的状态码更改为301或者302
    (4)当浏览器接收到返回之后,首先会去看状态码,如果是301或者302,浏览器会再次发送一个请求,请求地址为url2
  8.3 为了保证url的一致性,seo引擎优化
9、本地自动重启,开启调试模式
  app.run(debug=True)
10、另一种路由注册方法
 
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


def hello():
    headers = {
        'content-type': 'application/json',
    }
    return '<html></html>', 200, headers

app.add_url_rule('/hello', view_func=hello)


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
  
  注释掉@app.route('/hello')
  方法下面,添加app.add_url_rule('/hello', view_func=hello),类视图需要使用这种方式
11、启动配置
  app.run(host='0.0.0.0', debug=True) # 允许外网访问
  app.run(host='0.0.0.0', debug=True, port=8888) # 修改端口号
12、正式环境不能开启调试模式原因
  (1)调试模式使用的是flask自带的服务器,性能差
  (2)不能向用户展示任何网站的详细信息
13、配置文件
  正式环境和测试环境要保持镜像关系,就是代码一样
  config.py
  DEBUG = True
(1)配置文件中的配置都要大写,相当于常量,常量一般都大写
  
# -*- coding=utf-8 -*-
 
from flask import Flask
 
app = Flask(__name__)
app.config.from_object('config') # 载入配置文件,为模块路径
 
 
@app.route('/hello/')
def hello():
return 'Hello, World!'
 
 
app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=8888)
View Code
(2)注:
  如果将config.py中的DEBUG改为Debug,读取app.config['Debug']报错,from_object要求必须大写;
  如果config.py中为Debug = True,取的时候app.config['Debug']为False,因为Debug在flask中默认为False,就算没有设置,取值也为False
14、if __name__ == '__main__'
  14.1 如果入口文件中增加了这个判断之后,能够确保if里面的语句只在入口文件执行;
  14.2 如果当前的fisher.py文件不是作为入口文件直接被执行的,而是被其他模块导入的,下面的语句由于if的存在而不会被执行
  14.3 部署到生产环境不会使用flask自带的服务器,而是nginx+uwsgi
    生产环境使用uwsgi启动程序,fisher.py只是作为一个模块被传入,加上if判断,uwsgi启动的时候app.run便不会被执行,确保了安全性
15、response
  
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


@app.route('/hello')
def hello():
    return '<html></html>'

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
不显示任何东西
  15.1 视图函数
    (1)返回状态码,status code,200,404,301
    (2)返回content-type,放置于http的headers中,有值,告诉接收方如何解析主题内容,默认test/html
  15.2 返回的数据,封装成response对象
    (1)headers = {'content-type': 'text/plain'}
    (2)response = make_response('<html></html>', 404)
    (3)response.headers=headers
    (4)return response
  
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


@app.route('/hello')
def hello():
    headers = {
        'content-type': 'text/plain'
    }
    response = make_response('<html></html>', 404)
    response.headers = headers
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
    显示:<html></html>
  15.3 response与重定向
  
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


@app.route('/hello')
def hello():
    headers = {
        'content-type': 'text/plain',
        'location': 'http://www.baidu.com'
    }
    response = make_response('<html></html>', 301)
    response.headers = headers
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
    显示:百度首页
  15.4 返回json
  
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


@app.route('/hello')
def hello():
    headers = {
        'content-type': 'application/json',
    }
    response = make_response('{"a": 1, "name": "test"}', 200)
    response.headers = headers
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
    显示:以json方式展示
  15.4 最方便的返回方式
  
# -*- coding=utf-8 -*-

from flask import Flask, make_response

app = Flask(__name__)
app.config.from_object('config')


@app.route('/hello')
def hello():
    headers = {
    'content-type': 'application/json',
    }
    return '<html></html>', 200, headers

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=5000)
View Code
    显示:<html></html>
    本质:都是通过response的方式返回

猜你喜欢

转载自www.cnblogs.com/wangmingtao/p/9290919.html
今日推荐