如何在python中启用CORS

如何在python中启用CORS

本文介绍了如何在python中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我开始,我不了解python,我大概花了1天时间阅读python教程。情况就是这样。我有一个有角度的应用程序,在iframe中的vm上有一个由Apache托管的python应用程序。我没有编写python应用程序,但是另一个开发人员给我写了一个终结点,应该可以从我的有角度的应用程序中发布内容。

Let me start this with, I do not know python, I've had maybe 1 day going through the python tutorials. The situation is this. I have an angular app that has a python app hosted with Apache on a vm in an iframe. I didn't write the python app, but another developer wrote me an endpoint where I am supposed to be able to post from my angular app.

python端点说我的请求有问题,但我可以肯定没有任何问题。我几乎100%地确定问题是响应中没有CORS标头和/或未将响应设置为响应OPTIONS方法。以下是整个python端点:

The developer who made the python endpoint is saying that there is something wrong with my request but I am fairly certain there isn't anything wrong. I am almost 100% certain that the problem is that there are no CORS headers in the response and/or the response is not set up to respond to the OPTIONS method. Below is the entirety of the python endpoint:

import os, site, inspect
site.addsitedir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+"/../")
import json
from datetime import datetime

import pymongo

from Config import Config


def application(environ, start_response):
  response = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))

  if response:
    json_response = json.loads(response)

    document = {
      'payment_id': json_response['payment_id'],
      'log': json_response['log'],
      'login_id': json_response['login_id'],
      'browser': environ.get('HTTP_USER_AGENT', None),
      'ip_address': environ.get('REMOTE_ADDR', None),
      'created_at': datetime.utcnow(),
    }

    client = pymongo.MongoClient(Config.getValue('MongoServer'))
    db = client.updatepromise
    db.PaymentLogs.insert(document)

    start_response('200 OK', [('Content-Type', 'application/json')
    return '{"success": true}'

  start_response('400 Bad Request', [('Content-Type', 'application/json')])
  return '{"success": false}'

我已经尝试了以下方法来完成这项工作:我在start_response函数中添加了更多的标头,因此代码现在看起来像这样:

I have attempted the following to make this work: I added to both start_response functions more headers so the code looks like this now:

start_response('201 OK', [('Content-Type', 'application/json',
  ('Access-Control-Allow-Headers','authorization'),
  ('Access-Control-Allow-Methods','HEAD, GET, POST, PUT, PATCH, DELETE'),
  ('Access-Control-Allow-Origin','*'),
  ('Access-Control-Max-Age','600'))])

不是:起初,我同时使用200和400响应进行了此操作,但响应没有变化,仅此而已,我决定将200更改为201,这在响应s上也没有通过o我怀疑这段代码由于某种原因甚至无法运行。

Not: I did this both with the 200 and the 400 response at first, and saw no change at all in the response, then just for the heck of it, I decided to change the 200 to a 201, this also did not come through on the response so I suspect this code isn't even getting run for some reason.

请帮助,这里是python newb。

Please help, python newb here.

附录,我认为这会有所帮助,这是标题在响应中的样子:

Addendum, i figured this would help, here is what the Headers look like in the response:

General:

Request URL: http://rpc.local/api/payment_log_api.py
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 10.1.20.233:80
Referrer Policy: no-referrer-when-downgrade

Response Headers:

Allow: GET,HEAD,POST,OPTIONS
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/x-python
Date: Fri, 27 Apr 2018 15:18:55 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.18 (Ubuntu)

Request Headers:

Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization,content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: rpc.local
Origin: http://10.1.20.61:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36


推荐答案

在这里。只需在开始时将其添加到应用程序中即可:

Here it is. Just add this to the application right at the beginning:

def application(environ, start_response):
  if environ['REQUEST_METHOD'] == 'OPTIONS':
    start_response(
      '200 OK',
      [
        ('Content-Type', 'application/json'),
        ('Access-Control-Allow-Origin', '*'),
        ('Access-Control-Allow-Headers', 'Authorization, Content-Type'),
        ('Access-Control-Allow-Methods', 'POST'),
      ]
    )
    return ''

这篇关于如何在python中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:35