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

 上一篇文章中介绍了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)


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


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



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值