찾다
백엔드 개발파이썬 튜토리얼Python Flask는 도메인 간 문제를 해결합니다.

python 동영상 튜토리얼 칼럼에서는 도메인 간 문제를 해결하기 위한 Python Flask를 소개합니다.

Python Flask는 도메인 간 문제를 해결합니다.

목차

머리말사용 단계

    1. CORS 기능을 사용하세요. 글로벌 라우팅
  • 2. 단일 라인 라우팅을 구성하려면 @cross_origin을 사용하세요
  • 구성 매개변수 설명
    • Summary
      • Reference

      머리말CORS函数 配置全局路由

    • 2. 使用 @cross_origin 来配置单行路由
    • 配置参数说明
    • 总结
    • 参考

    • 前言

      我靠,又跨域了

      使用步骤

      1. 引入库

      pip install flask-cors复制代码

      2. 配置

      flask-cors 有两种用法,一种为全局使用,一种对指定的路由使用

      1. 使用 CORS函数 配置全局路由

      from flask import Flask, requestfrom flask_cors import CORS
      
      app = Flask(__name__)
      CORS(app, supports_credentials=True)复制代码

      其中 CORS 提供了一些参数帮助我们定制一下操作。

      常用的我们可以配置 originsmethodsallow_headerssupports_credentials

      所有的配置项如下:

      :param resources:
          The series of regular expression and (optionally) associated CORS
          options to be applied to the given resource path.
      
          If the argument is a dictionary, it's keys must be regular expressions,
          and the values must be a dictionary of kwargs, identical to the kwargs
          of this function.
      
          If the argument is a list, it is expected to be a list of regular
          expressions, for which the app-wide configured options are applied.
      
          If the argument is a string, it is expected to be a regular expression
          for which the app-wide configured options are applied.
      
          Default : Match all and apply app-level configuration
      
      :type resources: dict, iterable or string
      
      :param origins:
          The origin, or list of origins to allow requests from.
          The origin(s) may be regular expressions, case-sensitive strings,
          or else an asterisk
      
          Default : '*'
      :type origins: list, string or regex
      
      :param methods:
          The method or list of methods which the allowed origins are allowed to
          access for non-simple requests.
      
          Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
      :type methods: list or string
      
      :param expose_headers:
          The header or list which are safe to expose to the API of a CORS API
          specification.
      
          Default : None
      :type expose_headers: list or string
      
      :param allow_headers:
          The header or list of header field names which can be used when this
          resource is accessed by allowed origins. The header(s) may be regular
          expressions, case-sensitive strings, or else an asterisk.
      
          Default : '*', allow all headers
      :type allow_headers: list, string or regex
      
      :param supports_credentials:
          Allows users to make authenticated requests. If true, injects the
          `Access-Control-Allow-Credentials` header in responses. This allows
          cookies and credentials to be submitted across domains.
      
          :note: This option cannot be used in conjuction with a '*' origin
      
          Default : False
      :type supports_credentials: bool
      
      :param max_age:
          The maximum time for which this CORS request maybe cached. This value
          is set as the `Access-Control-Max-Age` header.
      
          Default : None
      :type max_age: timedelta, integer, string or None
      
      :param send_wildcard: If True, and the origins parameter is `*`, a wildcard
          `Access-Control-Allow-Origin` header is sent, rather than the
          request's `Origin` header.
      
          Default : False
      :type send_wildcard: bool
      
      :param vary_header:
          If True, the header Vary: Origin will be returned as per the W3
          implementation guidelines.
      
          Setting this header when the `Access-Control-Allow-Origin` is
          dynamically generated (e.g. when there is more than one allowed
          origin, and an Origin than '*' is returned) informs CDNs and other
          caches that the CORS headers are dynamic, and cannot be cached.
      
          If False, the Vary header will never be injected or altered.
      
          Default : True
      :type vary_header: bool复制代码

      2. 使用 @cross_origin 来配置单行路由

      from flask import Flask, requestfrom flask_cors import cross_origin
      
      app = Flask(__name__)@app.route('/')@cross_origin(supports_credentials=True)def hello():
          name = request.args.get("name", "World")    return f'Hello, {name}!'复制代码

      其中 cross_originCORS 提供一些基本相同的参数。

      常用的我们可以配置 originsmethodsallow_headerssupports_credentials

      所有的配置项如下:

      :param origins:
          The origin, or list of origins to allow requests from.
          The origin(s) may be regular expressions, case-sensitive strings,
          or else an asterisk
      
          Default : '*'
      :type origins: list, string or regex
      
      :param methods:
          The method or list of methods which the allowed origins are allowed to
          access for non-simple requests.
      
          Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
      :type methods: list or string
      
      :param expose_headers:
          The header or list which are safe to expose to the API of a CORS API
          specification.
      
          Default : None
      :type expose_headers: list or string
      
      :param allow_headers:
          The header or list of header field names which can be used when this
          resource is accessed by allowed origins. The header(s) may be regular
          expressions, case-sensitive strings, or else an asterisk.
      
          Default : '*', allow all headers
      :type allow_headers: list, string or regex
      
      :param supports_credentials:
          Allows users to make authenticated requests. If true, injects the
          `Access-Control-Allow-Credentials` header in responses. This allows
          cookies and credentials to be submitted across domains.
      
          :note: This option cannot be used in conjuction with a '*' origin
      
          Default : False
      :type supports_credentials: bool
      
      :param max_age:
          The maximum time for which this CORS request maybe cached. This value
          is set as the `Access-Control-Max-Age` header.
      
          Default : None
      :type max_age: timedelta, integer, string or None
      
      :param send_wildcard: If True, and the origins parameter is `*`, a wildcard
          `Access-Control-Allow-Origin` header is sent, rather than the
          request's `Origin` header.
      
          Default : False
      :type send_wildcard: bool
      
      :param vary_header:
          If True, the header Vary: Origin will be returned as per the W3
          implementation guidelines.
      
          Setting this header when the `Access-Control-Allow-Origin` is
          dynamically generated (e.g. when there is more than one allowed
          origin, and an Origin than '*' is returned) informs CDNs and other
          caches that the CORS headers are dynamic, and cannot be cached.
      
          If False, the Vary header will never be injected or altered.
      
          Default : True
      :type vary_header: bool
      
      :param automatic_options:
          Only applies to the `cross_origin` decorator. If True, Flask-CORS will
          override Flask's default OPTIONS handling to return CORS headers for
          OPTIONS requests.
      
          Default : True
      :type automatic_options: bool复制代码

      配置参数说明

      参数 类型 Head 默认 说明
      resources 字典、迭代器或字符串 全部 配置允许跨域的路由接口
      origins 列表、字符串或正则表达式 Access-Control-Allow-Origin * 配置允许跨域访问的源
      methods 列表、字符串 Access-Control-Allow-Methods [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] 配置跨域支持的请求方式
      expose_headers 列表、字符串 Access-Control-Expose-Headers None 自定义请求响应的Head信息
      allow_headers 列表、字符串或正则表达式 Access-Control-Request-Headers * 配置允许跨域的请求头
      supports_credentials 布尔值 Access-Control-Allow-Credentials False 是否允许请求发送cookie
      max_age timedelta、整数、字符串 Access-Control-Max-Age None 预检请求的有效时长

      总结

      在 flask 的跨域配置中,我们可以使用 flask-cors 来进行配置,其中 CORS 函数 用来做全局的配置, @cross_origin

      젠장, 또 크로스 도메인이군요

      사용 단계

      1. 라이브러리 가져오기

      rrreee

      2. 구성

      flask-cors에는 두 가지 용도가 있습니다. 하나는 전역 사용용이고 다른 하나는 지정된 경로용입니다.

      1. CORS 기능을 사용하여 전역 라우팅을 구성합니다.

      rrreee여기서 CORS는 몇 가지 매개변수를 제공합니다. 작업을 사용자 정의합니다. 일반적으로 사용되는 origins, methods, allow_headers, supports_credentials를 구성할 수 있습니다
      모든 구성 항목은 다음과 같습니다. :🎜🎜rrreee

      2. @cross_origin을 사용하여 단일 회선 라우팅을 구성합니다.

      rrreee🎜여기서 cross_origin CORS는 본질적으로 동일한 매개변수를 제공합니다. 🎜🎜일반적으로 사용되는 origins, methods, allow_headers, supports_credentials를 구성할 수 있습니다🎜🎜🎜모든 구성 항목은 다음과 같습니다. 다음 :🎜🎜rrreee

      구성 매개변수 설명

      없음
      매개변수 유형 헤드 기본값 설명 번째>
      리소스 사전, 반복자 또는 문자열모두 교차 도메인 라우팅을 허용하는 라우팅 인터페이스 구성
      원본 목록, 문자열 또는 정규 표현식 Access-Control-Allow-Origin * 교차 도메인 액세스를 허용하는 소스 구성
      메소드 목록, 문자열 접근 제어 허용 메소드 [GET , HEAD, POST, OPTIONS, PUT, PATCH, DELETE] 교차 도메인 지원을 위한 요청 방법 구성
      노출_헤더 목록, 문자열 액세스 제어-노출-헤더 없음 요청 응답 헤드 정보 사용자 정의
      allow_headers 목록, 문자열 또는 정규 표현식 Access-Control-Request-Headers * 교차 도메인 요청 헤더 구성
      supports_credentials 부울 값 Access-Control-Allow-Credentials False 쿠키 전송 요청 허용 여부
      max_age timedelta, 정수, 문자열 Access-Control-Max-Age 없음 실행 전 요청의 유효 기간

      요약🎜🎜Flask의 도메인 간 구성에서는 구성에 flask-cors를 사용할 수 있으며, 여기서 CORS 함수는 전역 구성에 사용됩니다. @cross_origin을 사용하여 특정 경로의 구성을 구현합니다. 🎜🎜🎜🎜더 많은 관련 무료 학습 권장사항: 🎜🎜🎜python 비디오 튜토리얼🎜🎜🎜🎜

      위 내용은 Python Flask는 도메인 간 문제를 해결합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

      성명
      이 기사는 juejin에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
      파이썬 : 게임, Guis 등파이썬 : 게임, Guis 등Apr 13, 2025 am 12:14 AM

      Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

      Python vs. C : 응용 및 사용 사례가 비교되었습니다Python vs. C : 응용 및 사용 사례가 비교되었습니다Apr 12, 2025 am 12:01 AM

      Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

      2 시간의 파이썬 계획 : 현실적인 접근2 시간의 파이썬 계획 : 현실적인 접근Apr 11, 2025 am 12:04 AM

      2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

      파이썬 : 기본 응용 프로그램 탐색파이썬 : 기본 응용 프로그램 탐색Apr 10, 2025 am 09:41 AM

      Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 ​​같은 작업에 적합합니다.

      2 시간 안에 얼마나 많은 파이썬을 배울 수 있습니까?2 시간 안에 얼마나 많은 파이썬을 배울 수 있습니까?Apr 09, 2025 pm 04:33 PM

      2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

      10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법?10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법?Apr 02, 2025 am 07:18 AM

      10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

      중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까?중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까?Apr 02, 2025 am 07:15 AM

      Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

      Python 3.6에 피클 파일을로드 할 때 '__builtin__'모듈을 찾을 수없는 경우 어떻게해야합니까?Python 3.6에 피클 파일을로드 할 때 '__builtin__'모듈을 찾을 수없는 경우 어떻게해야합니까?Apr 02, 2025 am 07:12 AM

      Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

      See all articles

      핫 AI 도구

      Undresser.AI Undress

      Undresser.AI Undress

      사실적인 누드 사진을 만들기 위한 AI 기반 앱

      AI Clothes Remover

      AI Clothes Remover

      사진에서 옷을 제거하는 온라인 AI 도구입니다.

      Undress AI Tool

      Undress AI Tool

      무료로 이미지를 벗다

      Clothoff.io

      Clothoff.io

      AI 옷 제거제

      AI Hentai Generator

      AI Hentai Generator

      AI Hentai를 무료로 생성하십시오.

      인기 기사

      R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
      3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
      R.E.P.O. 최고의 그래픽 설정
      3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
      R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
      3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
      WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
      4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

      뜨거운 도구

      맨티스BT

      맨티스BT

      Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

      MinGW - Windows용 미니멀리스트 GNU

      MinGW - Windows용 미니멀리스트 GNU

      이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

      ZendStudio 13.5.1 맥

      ZendStudio 13.5.1 맥

      강력한 PHP 통합 개발 환경

      에디트플러스 중국어 크랙 버전

      에디트플러스 중국어 크랙 버전

      작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

      스튜디오 13.0.1 보내기

      스튜디오 13.0.1 보내기

      강력한 PHP 통합 개발 환경