码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】Bottle框架下Python Web开发的跨域访问

时间:2015-01-31 14:36:17      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:python   web   bottle   跨域访问   

 上一篇文章中介绍了Python应用Bottle轻量级框架进行Web开发,这次介绍Bottle框架下的跨域访问的问题。


       当前台跨域访问时,会无法从后台得到数据,也就是说跨域访问失败。

解决办法如下:

在程序中定义一个函数代码如下:

#!/usr/bin/python
# -*- conding:utf-8 -*-

from bottle import *

#decorator
def allow_cross_domain(fn):
    def _enable_cors(*args, **kwargs):
        #set cross headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,OPTIONS'
        allow_headers = 'Referer, Accept, Origin, User-Agent'
        response.headers['Access-Control-Allow-Headers'] = allow_headers     
        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)    
    return _enable_cors
	

@route('/helloworld/:yourwords', methods=['GET', 'POST'])
@allow_cross_domain                                              #在此处加上定义的函数
def hello(yourwords):
	return 'hello world. ' + yourwords

run(host='0.0.0.0', port=8080)


如上代码中所示,在每次调用时,加上该用于跨域的函数即可解决跨域访问的问题。


希望对大家有所帮助。谢谢。



【Python】Bottle框架下Python Web开发的跨域访问

标签:python   web   bottle   跨域访问   

原文地址:http://blog.csdn.net/xiaoguaihai/article/details/43340701

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!