Flask
- Flask默认端口号是5000
安装
- 可以直接在电脑环境下pip install flask
- 也可以在virtualenv环境下安装来控制版本
- 推荐第二种
实例应用
路由开启服务器
- 路由默认是GET方法
- 这里的请求头经常出bug
# coding=utf-8
from flask import Flask, request, url_for # 这里的request不是Requests中的requests,只安装Flask即可
app = Flask(__name__)
@app.route('/', methods=['POST'])
def hello():
return "<h1>hello world<h1>" # 可以添加标签来改变样式
@app.route('/index', methods=['POST', 'GET'])
def index():
print(request.headers) # 取到HTTP的请求头,会在控制台输出
return(str(request.headers))
@app.route('/index/<user>', methods=['POST'])
def hello(user):
print(request.headers) # 取到HTTP的请求头,会在控制台输出
return 'hello : %s' % user
@app.route('/query_user', methods = ['GET', 'POST'])
def query_user(): # 另一种传参数的方法,localhost:5000/query_user?id=123456 进行查询,可以GET,也可以POST
id = request.args.get('id')
return 'query_user:' + id
@app.route('/query_url') # 反向路由
def query_url():
return 'query url:' + url_for('query_user')
if __name__ == '__main__':
app.debug = True # 设置debug模式,每次修改保存后自动重启
app.run()
模板的应用 继承 传递 render_template
- HTML模板要放到..\templates\中,这里给出了HTML文件的body标签中的内容
********# models.py
class User(object):
def __init__(self, user_id, user_name):
self.user_id = user_id
self.user_name = user_name
********# flaskapp.py
# coding=utf-8
from flask import Flask, render_template
from models import User
app = Flask(__name__)
@app.route('/')
def hello_world():
content = "Hello world"
return render_template("index.html", content=content)
''' # index.html
<html><head lang="en"></head><body>
<h1>{{ content }}</h1>
</body></html>
'''
@app.route('/user')
def user_index():
user = User(1, 'jikexueyuan')
return render_template("user_index.html", user=user)
''' # user_index.html
<html><head lang="en"></head><body>
<h1>hello {{ user.user_name }}</h1>
</body></html>
'''
@app.route('/query_user/<user_id>') # 条件语句
def query_user(user_id):
user = None
if int(user_id) == 1:
user = User(1, 'jikexueyuan')
return render_template("user_id.html", user=user)
''' # user_id.html
<html><head lang="en"></head><body>
{% if user %}
hello {{ user.user_name }}
{% else %}
no this user
{% endif %}
</body></html>
'''
@app.route('/users')
def user_list():
users = []
for i in range(1, 11):
user = User(i, 'jikexueyuan' + str(i))
users.append(user)
return render_template("user_list.html", users=users)
''' # user_list.html
<html><head lang="en"></head><body>
{% for user in users %}
{{ user.user_id }}--{{ user.user_name }}<br>
{% endfor %}
</body></html>
'''
@app.route('/one') # 这里是继承的应用
def one_base():
return render_template("one_base.html")
''' # base.html
<html><head lang="en"></head><body>
<div>
<h1>Header 极客学院</h1>
</div>
{% block content %}
{% endblock %}
<div>
<h1>Footer jikexueyuan</h1>
</div>
</body></html>
'''
''' # one_base.html
{% extends "base.html" %}
{% block content %}
<h2>这是第一页</h2>
{% endblock %}
'''
@app.route('/two')
def two_base():
return render_template("two_base.html")
''' # two_base.html
{% extends "base.html" %}
{% block content %}
<h2>这是第二页</h2>
{% endblock %}
'''
if __name__ == '__main__':
app.debug = True
app.run()
消息提示于异常处理 flash
# coding=utf-8
from flask import Flask, flash, render_template, request, abort
app = Flask(__name__)
app.secret_key = '123' # flask加密方式
@app.route('/login', methods=['POST'])
def login():
form = request.form # 接受前端传过来的表单
username = form.get('username')
password = form.get('password')
if not username:
flash("please input username")
return render_template("index.html")
if not password:
flash("please input password")
return render_template("index.html")
if username == 'jikexueyuan' and password == '123456':
flash("login success")
return render_template("index.html")
else:
flash("username or password is wrong")
return render_template("index.html")
''' # index.html
<html><head lang="en"></head><body>
<h1>Hello Login</h1>
<form action="/login" method="post">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="Submit"/>
</form>
<h2>{{ get_flashed_messages()[0] }}</h2>
</body></html>
'''
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
''' # 404.html
<html><head lang="en"></head><body>
<h1>你要找的页面去火星了</h1>
<h2>抱歉!该页面不存在</h2>
</body></html>
'''
@app.route('/users/<user_id>')
def users(user_id):
if int(user_id) == 1:
return render_template("user.html")
else:
abort(404)
''' # user.html
<html><head lang="en"></head><body>
<h1>User</h1>
</body></html>
'''
if __name__ == '__main__':
app.debug=True
app.run()
token
- Flask端
# -*- coding: utf-8 -*-
import base64
import random
import time
from flask import Flask, request
app = Flask(__name__)
users = {
"magigo": ["123456"]
}
def gen_token(uid):
token = base64.b64encode(':'.join([str(uid), str(random.random()), str(time.time() + 7200)]))
users[uid].append(token)
return token
def verify_token(token):
_token = base64.b64decode(token)
if not users.get(_token.split(':')[0])[-1] == token:
return -1
if float(_token.split(':')[-1]) >= time.time():
return 1
else:
return 0
@app.route('/index', methods=['POST', 'GET'])
def index():
print request.headers
return 'hello'
@app.route('/login', methods=['POST', 'GET'])
def login():
uid, pw = base64.b64decode(request.headers['Authorization'].split(' ')[-1]).split(':')
if users.get(uid)[0] == pw:
return gen_token(uid)
else:
return 'error'
@app.route('/test1', methods=['POST', 'GET'])
def test():
token = request.args.get('token')
if verify_token(token) == 1:
return 'data'
else:
return 'error'
if __name__ == '__main__':
# app.debug = True
app.run(debug=True)
利用restful编写
from flask import Flask
from flask.ext import restful
app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
def get(self):
return {"hello": "world"}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run()
Requests端
# -*- coding: utf-8 -*-
import requests
r = requests.get('http://127.0.0.1:5000/login', auth=('magigo', '123456'))
print r.text
token ='bWFnaWdvOjAuMjg2ODI4OTE4NzE1OjE0NTMwNDA0MDguNDY='
r = requests.get('http://127.0.0.1:5000/test1', params={'token': token})
print r.text
Requests HTTP for Humans
安装
- $ pip install requests
- $ git clone git://github.com/kennethreitz/requests.git
- $ python setup.py install
- 或者
- $ py -2 setup.py install
应用实例
查看requests默认请求头
- 先去在virtualenv安装requests,这里的请求头经常出bug
//Flask 在虚拟环境下执行
@app.route('/index', methods=['POST', 'GET'])
def index():
print(request.headers) # 取到HTTP的请求头,会在控制台输出
return(str(request.headers))
//test.py 在外部环境下执行
import requests
r = requests.get('http://127.0.0.1:5000/index')
print(r.text)
控制台中会显示
Content-Length:
User-Agent: python-requests/2.9.1 # requests默认请求头
Connection: keep-alive
Host: 127.0.0.1:5000
Accept: */*
Content-Type:
Accept-Encoding: gzip, deflate
获得真正请求头
- 去开发者工具中的Network选项卡中找一个Header的User-Agent
- 再看控制台返回的信息,信息头已经变了
import requests
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}
r = requests.get('http://127.0.0.1:5000/index', headers=headers)
print(r.text)
get请求
import requests
r = requests.get('http://httpbin.org/get')
print r.text
'''
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, compress",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.2.1 CPython/2.7.6 Linux/3.19.0-54-generic"
},
"origin": "222.195.191.93",
"url": "http://httpbin.org/get"
}
'''
发送带参数的get请求,将key与value放入一个字典中,通过params参数来传递,其作用相当于urllib.urlencode
>>> import requests
>>> pqyload = {'q':'杨彦星'}
>>> r = requests.get('http://www.so.com/s',params = pqyload)
>>> r.url
u'http://www.so.com/s?q=%E6%9D%A8%E5%BD%A6%E6%98%9F'
发送post请求,通过data参数来传递
>>> payload = {'a':'杨','b':'hello'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
"args": {},
"data": "",
"files": {},
"form": {
"a": "u6768",
"b": "hello"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "19",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.3.0 CPython/2.6.6 Windows/7",
"X-Request-Id": "c81cb937-04b8-4a2d-ba32-04b5c0b3ba98"
},
"json": null,
"origin": "124.192.129.84",
"url": "http://httpbin.org/post"
}
>>>
可以看到,post参数已经传到了form里,data不光可以接受字典类型的数据,还可以接受json等格式
>>> payload = {'a':'杨','b':'hello'}
>>> import json
>>> r = requests.post('http://httpbin.org/post', data=json.dumps(payload))
{
"args": {},
"data": "{\"a\": \"\\u6768\", \"b\": \"hello\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, compress",
"Content-Length": "29",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.2.1 CPython/2.7.6 Linux/3.19.0-54-generic"
},
"json": {
"a": "\u6768",
"b": "hello"
},
"origin": "222.195.191.93",
"url": "http://httpbin.org/post"
}
发送文件的post类型
- 这个相当于向网站上传一张图片,文档等操作,这时要使用files参数
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('touxiang.png', 'rb')}
>>> r = requests.post(url, files=files)
定制headers,使用headers参数来传递
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
响应内容
响应状态码
>>> r = requests.get(‘http://httpbin.org/get‘)
>>> print r.status_code
200
响应头
>>> print r.headers
{'content-length': '519', 'server': 'gunicorn/18.0', 'connection': 'keep-alive', 'date': 'Sun, 15 Jun 2014 14:19:52 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}
也可以取到这个个别的响应头用来做一些判断,这里的参数是不区分大小写的
print r.headers['Content-Type']
print r.headers.get('Content-Type')
获取响应中的cookies
>>> r = requests.get('http://www.baidu.com')
>>> r.cookies['BAIDUID']
'D5810267346AEFB0F25CB0D6D0E043E6:FG=1'
也可以自已定义请求的COOKIES
>>> url = 'http://httpbin.org/cookies'
>>> cookies = {'cookies_are':'working'}
>>> r = requests.get(url,cookies = cookies)
>>>
>>> print r.text
{
"cookies": {
"cookies_are": "working"
}
}
>>>
使用timeout参数设置超时时间
>>> requests.get('http://github.com', timeout=1)
<Response [200]>
- 如果将时间设置成非常小的数,如requests.get(‘http://github.com’, timeout=0.001),那么如果在timeout的时间内没有连接,那么将会抛出一个Timeout的异常
访问中使用session
- 先初始化一个session对象,s = requests.Session()
- 然后使用这个session对象来进行访问,r = s.post(url,data = user)
- 参考文章 http://blog.csdn.net/iloveyin/article/details/21444613 基本上都是从这扒的代码
- 以下通过访问人人网来获取首页中的最近来访问,然后再访问查看更多的来访来读取更多的最近来访
- 20151029更新,由于很久没有登录人人网,它的登录页面与获得最近来访的页面都有所变动,登录时的url是http://www.renren.com/ajaxLogin/login 获取最近来访是http://www.renren.com/myfoot/whoSeenMe
- 更多的来访就是以带session的访问http://www.renren.com/myfoot/whoSeenMe
#coding:utf-8
import requests
import re
url = r'http://www.renren.com/PLogin.do'
user = {'email':'email','password':'pass'}
s = requests.Session()
r = s.post(url,data = user)
'''''''''''''''''''''''''''''''
html = r.text
visit = []
first = re.compile(r'</span><span class="time-tip first-tip"><span class="tip-content">(.*?)</span>')
second = re.compile(r'</span><span class="time-tip"><span class="tip-content">(.*?)</span>')
third = re.compile(r'</span><span class="time-tip last-second-tip"><span class="tip-content">(.*?)</span>')
last = re.compile(r'</span><span class="time-tip last-tip"><span class="tip-content">(.*?)</span>')
visit.extend(first.findall(html))
visit.extend(second.findall(html))
visit.extend(third.findall(html))
visit.extend(last.findall(html))
for i in visit:
print i
''''''''''''''''''''''''''''''''''''''''''''
print '以下是更多的最近来访'
vm = s.get('http://www.renren.com/myfoot/whoSeenMe')
fm = re.compile(r'"name":"(.*?)"')
visitmore = fm.findall(vm.text)
for i in visitmore:
print i
- 会以列表的形式输出最近的访客