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

yipeiwu_com6年前Python基础

使用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解决跨域问题实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python二分法搜索算法实例分析

本文实例分析了Python二分法搜索算法。分享给大家供大家参考。具体分析如下: 今天看书时,书上提到二分法虽然道理简单,大家一听就明白但是真正能一次性写出别出错的实现还是比较难的,即使给...

python中Flask框架简单入门实例

本文实例讲述了python中Flask框架的简单用法。分享给大家供大家参考。具体如下: 使用Flask框架的简单入门范例代码,如果你正学习Flask框架,可以参考下面的启动代码,这段代码...

python中将字典转换成其json字符串

#这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': {...

用python实现的可以拷贝或剪切一个文件列表中的所有文件

复制代码 代码如下:# coding:utf-8 import os import sys def cut_and_paste_file(source, destination): &n...

python数据库操作常用功能使用详解(创建表/插入数据/获取数据)

实例1、取得MYSQL版本 复制代码 代码如下:# -*- coding: UTF-8 -*-#安装MYSQL DB for pythonimport MySQLdb as mdbco...