web.py header_跨域.py

"""
测试 URL:
    http://localhost:8080/
    http://localhost:8080/2d

知识点:
    0.Help on function header in module web.webapi:
        web.header(hdr, value, unique=False)
            指定响应头。
            Adds the header `hdr: value` with the response.

            If `unique` is True and a header with that name already exists,
            it doesn't add a new one.

    1.web.header
        web.header('content-type', 'application/json; charset=utf-8')
        # web.header('content-type', 'text/json; charset=utf-8')
            指定响应头的内容类型及编码。可解决中文乱码。
            即,返回的数据类型,编码。
            在前端的话,就指发送到后端的数据类型。
            都是指要给对方的。
        web.header("Access-Control-Allow-Origin", "*")
            指定允许访问的域名,如:http://ip:port/
        web.header("Access-Control-Allow-Methods", "GET, POST,PUT,DELETE,OPTIONS")
        web.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization")
"""
import web

urls = (
    '/2d', 'getConfig2d',
    '/', 'getConfig'
)


class getConfig2d:
    def GET(self):
        """
        此方法适用于,前端类似这样的请求:
        $.getJSON("http://localhost:8080/2d", function (data) {
            // data, 即请求json文件的内容,且data为json格式。
        });
        """
        web.header('content-type', 'text/json; charset=utf-8')
        web.header("Access-Control-Allow-Origin", "*")
        file = 'C:/Users/asus/Desktop/gaoshengjie/localServers/config2d.json'
        f = open(file, 'rb').read()
        return f


class getConfig:
    """
    此类中两种方法,适用于,首先有OPTIONS请求,然后有GET请求的场景。
    前端请求类似这样:
    mars3d.createMap({
        id: 'cesiumContainer',
        // url: configfile + "?time=20180616",
        url: "http://localhost:8080/?time=20180616",
        //infoBox: false,     //是否显示点击要素之后显示的信息  【也可以在config.json中配置】
        //shadows : true,

        layerToMap: layerToMap,
        success: function (_viewer, gisdata, jsondata) { //地图成功加载完成后执行
        }
    });
    """

    def GET(self):
        web.header("Access-Control-Allow-Origin", "*")
        file = 'C:/Users/asus/Desktop/gaoshengjie/localServers/config.json'
        f = open(file, 'rb').read()
        return f

    def OPTIONS(self):
        """
        预检请求。
        跨域请求中的非简单请求,需要设置 访问控制允许的请求头 和 方法。
        :return:
        """
        web.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization")
        web.header("Access-Control-Allow-Methods", "GET, POST")


if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值