python解决跨域问题_python web.py开发httpserver解决跨域问题实例解析

使用web.py做http server开发时,遇到postman能够正常请求到数据,但是浏览器无法请求到数据,查原因之后发现是跨域请求的问题。

跨域请求,就是在浏览器窗口中,和某个服务端通过某个 “协议+域名+端口号” 建立了会话的前提下,去使用与这三个属性任意一个不同的源提交了请求,那么浏览器就认为你是跨域了,违反了浏览器的同源策略。 w3c标准中,有针对跨域请求的规范,在响应头中有以下三种跨域访问限制:

Access-Control-Allow-Origin:限制允许跨域访问的源,比如http://192.168.10.12:8080,注意这里仅仅支持*(表示所有源)号或者某个源,不支持多个源,如果要实现多个源,可以自己包装一个集合,对每次的请求在集合中判断是否存在,如存在,就放到响应头中来;

Access-Control-Allow-Methods:限制允许跨域访问的http方法类型,多个以逗号隔开,比如:POST, GET, OPTIONS,PUT, DELETE

Access-Control-Allow-Headers:限制允许跨域访问的http头部,包含这里设置的头,才允许跨域访问,比如:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization

web.py使用web.header(),可以定义header。

完整的httpserver代码如下【ap-httpserver.py】:

#!/usr/bin/env python

# encoding: utf-8

import redis

import web

import json

import string

from time import time

urls = (

'/qlljx/realtimedata', 'realtimedata'

)

app = web.application(urls, globals())

def getResult():

r = redis.Redis(host='127.0.0.1', port=6379)

result_list = []

regionlist = r.hgetall('regionlist')

timestamp = r.hget('zhongguo_bgp', 'timestamp')

for region in regionlist:

value = {'mip': str(regionlist[region]), 'region': region, \

'inpps': int(r.hget(region, 'inpps')), 'outpps': int(r.hget(region, 'outpps')), \

'inbps': int(r.hget(region, 'inbps')), 'outbps': int(r.hget(region, 'outbps')), \

'pktpct': string.atof(r.hget(region, 'pktpct')), 'bytpct': string.atof(r.hget(region, 'bytpct'))}

result_list.append(value)

result = {'timestamp': timestamp, 'result': result_list}

return json.dumps(result)

class realtimedata:

def POST(self):

data = web.data()

request_type = str(json.loads(data)['type'])

if request_type == 'getRealTimeData':

result = getResult()

web.header("Access-Control-Allow-Origin", "*")

#web.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")

#web.header("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, \

# Accept-Encoding, X-CSRF-Token, Authorization")

return result

if __name__ == "__main__":

app.run()

其中只使用了"Access-Control-Allow-Origin" 限制,允许所有源的请求。启动httpserver:

[root@localhost python]# ./ap-httpserver.py 1216

使用浏览器请求数据正常了。

总结

以上就是本文关于python web.py开发httpserver解决跨域问题实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值