python 部分模块
l Import sys
当Python执行import sys语句的时候,它在sys.path变量中所列目录中寻找sys.py模块。如果找到了这个文件,这个模块的主块中的语句将被运行,然后这个模块将能够被你 使用 。注意,初始化过程仅在我们 第一次 输入模块的时候进行。另外,“sys”是“system”的缩写。
l Import os
os.path.abspath(path) 返回path的绝对路径
os.path.split(path) 将path分割成目录和文件名并以元组方式返回
os.path.dirname(path) 返回path的目录,其实就是返回os.path.split(path)元组的第一个元素
os.path.basename(path) 返回path的文件名,其实就是返回os.path.split(path)元组的第二个元素
l import argparse
定义:argparse是python标准库里面用来处理命令行参数的库
命令行参数分为位置参数和选项参数:
位置参数就是程序根据该参数出现的位置来确定的
如:[root@openstack_1 /]# ls root/ #其中root/是位置参数
选项参数是应用程序已经提前定义好的参数,不是随意指定的
如:[root@openstack_1 /]# ls -l # -l 就是ls命令里的一个选项参数
argparse.ArgumentParser()方法参数须知:
一般我们只选择用description
prog=None - 程序名
description=None, - help时显示的开始文字
epilog=None, - help时显示的结尾文字
parents=[], -若与其他参数的一些内容一样,可以继承
formatter_class=argparse.HelpFormatter, - 自定义帮助信息的格式
prefix_chars='-', - 命令的前缀,默认是‘-’
fromfile_prefix_chars=None, - 命令行参数从文件中读取
argument_default=None, - 设置一个全局的选项缺省值,一般每个选项单独设置
conflict_handler='error', - 定义两个add_argument中添加的选项名字发生冲突时怎么处理,默认处理是抛出异常
add_help=True - 是否增加-h/--help选项,默认是True)
Flask 中make_responsem模块
make_response(),相当于DJango中的HttpResponse。
1.返回内容
from flask import make_response
@blue.route('/makeresponse/')
def make_response_function():
response = make_response('<h2>羞羞哒</h2>')
return response, 404
2.返回页面
from flask import make_response
@blue.route('/makeresponse/')
def make_response_function():
temp = render_template('hello.html')
response = make_response(temp)
return response
>>>注意:make_response 想要返回页面,不能直接写做:make_response('hello.html'),必须用render_template('hello.html')形式。
3.返回状态码
>>>方式一:在make_response()中传入状态码
from flask import make_response
@blue.route('/makeresponse/')def make_response_function():
temp = render_template('hello.html')
response = make_response(temp, 200)
return response
>>>方式二:直接return状态码
from flask import make_response
@blue.route('/makeresponse/')
def make_response_function():
temp = render_template('hello.html')
response = make_response(temp)
return response, 200
l 1. app.add_url_rule()函数
在flask中,我们知道给一个函数添加url的时候,只需要使用装饰器@app.route('<url>')装饰对应的函数就可以了。为什么这个装饰器就可以给函数视图 添加url规则呢?查看app.route()源码发现,这个装饰器在里面调用的另外一个方法self.add_url_rule,这里的self就是app这个实例对象。
app.route()源码内容
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
那么app.route这个装饰器就是通过调用add_url_rule这个方法生成函数视图对应的url的,那么我们可不可以我们自己直接调用这个方法来生成函数对应的url规则呢?答案是肯定的。
示例如下:
from flask import Flask
app = Flask(__name__)
def index():
return 'index'
app.add_url_rule('/index/',endpoint='index',view_func=index)
add_url_rule三个参数解释:
第一个参数:函数对应的url规则,满足条件和app.route()的第一个参数一样,必须以'/'开始
endpoint:站点,就是在使用url_for()进行反转的时候,这个里面传入的第一个参数就是这个endpoint对应的值。这个值也可以不指定,那么默认就会使用函数的名字作为endpoint的值
view_func:对应的函数,即这个url对应的是哪一个函数,注意,这里函数只需要写函数名字,不要加括号,加括号表示将函数的返回值传给了view_func参数了。程序就会直接报错。
# 正确的方式
app.add_url_rule('/index/',endpoint='index',view_func=index)
# 错误的方式
app.add_url_rule('/index/',endpoint='index',view_func=index())
methods:add_url_rule还可以传入一个methods参数,用来指定这个函数对应的访问规制,如post,get请求等,默认是get请求,并且只允许get请求。当我们需要改变请求方式的时候,我们就可以传入这个参数了。
# 指定一种
app.add_url_rule('/index/',endpoint='index',view_func=index,methods=['POST'])
# 指定多种
app.add_url_rule('/index/',endpoint='index',view_func=index,methods=['POST','get'])
l Flask-cors跨域
跨域(跨源)是指浏览器从一个源的网页去请求另一个源,源指的是域名、端口、协议
以下都属于跨域问题
域名:
主域名不同: http://www.baidu.com/index.html –> http://www.sina.com/test.js
子域名不同: http://www.666.baidu.com/index.html –> http://www.555.baidu.com/test.js
域名和域名ip: http://www.baidu.com/index.html –>http://180.149.132.47/test.js
端口:
http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/test.js
协议:
http://www.baidu.com:8080/index.html–> https://www.baidu.com:8080/test.js
Flask支持跨域
安装flask_cors
pip install flask-cors
使用flask_cors的CORS
from flask_cors import CORS
CORS(app, supports_credentials=True)
l python 的 sys.path.append()
当我们导入一个模块时:import xxx,默认情况下python解析器会搜索当前目录、已安装的内置模块和第三方模块,搜索路径存放在sys模块的path中:
>>> import sys
>>> sys.path
['', 'C:\\Python352\\Lib\\idlelib',
'C:\\Python352\\python35.zip',
'C:\\Python352\\DLLs',
'C:\\Python352\\lib',
'C:\\Python352',
'C:\\Python352\\lib\\site-packages', 'C:\\Python352\\lib\\site-packages\\setuptools-28.6.1-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\pip-8.1.2-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\requests-2.11.1-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\xlutils-2.0.0-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\xlwt-1.1.2-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\pymongo-3.3.1-py3.5-win-amd64.egg', 'C:\\Python352\\lib\\site-packages\\pytz-2016.7-py3.5.egg', 'C:\\Python352\\lib\\site-packages\\zope.interface-4.3.3-py3.5-win-amd64.egg']
sys.path 返回的是一个列表!
该路径已经添加到系统的环境变量了,当我们要添加自己的搜索目录时,可以通过列表的append()方法;
对于模块和自己写的脚本不在同一个目录下,在脚本开头加sys.path.append('xxx'):
import sys
sys.path.append(’引用模块的地址')
这种方法是运行时修改,脚本运行后就会失效的。
另外一种方法是:
把路径添加到系统的环境变量,或把该路径的文件夹放进已经添加到系统环境变量的路径内。环境变量的内容会自动添加到模块搜索路径中。
l app = Flask(__name__) 是个什么东西
"""第一部分,初始化:所有的Flask都必须创建程序实例,
web服务器使用wsgi协议,把客户端所有的请求都转发给这个程序实例
程序实例是Flask的对象,一般情况下用如下方法实例化
Flask类只有一个必须指定的参数,即程序主模块或者包的名字,__name__是系统变量,该变量指的是本py文件的文件名"""
from flask import Flask
app = Flask(__name__)
# 第二部分,路由和视图函数:
# 客户端发送url给web服务器,web服务器将url转发给flask程序实例,程序实例
# 需要知道对于每一个url请求启动那一部分代码,所以保存了一个url和python函数的映射关系。
# 处理url和函数之间关系的程序,称为路由
# 在flask中,定义路由最简便的方式,是使用程序实例的app.route装饰器,把装饰的函数注册为路由
@app.route('/')
def hello_world():
return __name__
# 第三部分:程序实例用run方法启动flask集成的开发web服务器
# __name__ == '__main__'是python常用的方法,表示只有直接启动本脚本时候,才用app.run方法
# 如果是其他脚本调用本脚本,程序假定父级脚本会启用不同的服务器,因此不用执行app.run()
# 服务器启动后,会启动轮询,等待并处理请求。轮询会一直请求,直到程序停止。
if __name__ == '__main__':
print('dd',__name__)
app.run()
l app.add_url_rule('/list/',endpoint='zhiliao',view_func=my_list)
#以上方法是用来添加url和视图函数的映射关系
#endpoint其实只是指定了此url的名字,view_func里面指定视图函数的名字。通过以上方式,访问list,跳转到列表页面
#如果已经指定了endpoint,url_for 指定的时候,就不能用视图函数的名字,直接用endpoint的名字
#下面用钩子函数举例
#先在首页endpoint命名为 index
with app.test_request_context():
print(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
l os.path.abspath()
返回一个目录的绝对路径
1.os.path.realpath()
返回指定文件的标准路径,而非软链接所在的路径
l os.path.join()函数:
连接两个或更多的路径名组件
1.如果各组件名首字母不包含’/’,则函数会自动加上
2.如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃
3.如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾
l insert_one(data)
update_one({'info': data['info']}, {'$set': data}, True)
更新的方法:
参数1:指定根据什么字段去数据库中进行查询,字段的值。
参数2:如果经过参数1的查询,查询到这条数据,执行更新的操作;反之,执行插入的操作;$set是一个固定的写法。
参数3:是否允许更新

浙公网安备 33010602011771号