목차
목차
머리말CORS函数 配置全局路由
前言
使用步骤
1. 引入库
2. 配置
1. 使用 CORS函数 配置全局路由
2. 使用 @cross_origin 来配置单行路由
配置参数说明
总结
사용 단계
1. 라이브러리 가져오기
2. 구성
1. CORS 기능을 사용하여 전역 라우팅을 구성합니다.
2. @cross_origin을 사용하여 단일 회선 라우팅을 구성합니다.
구성 매개변수 설명
요약🎜🎜Flask의 도메인 간 구성에서는 구성에 flask-cors를 사용할 수 있으며, 여기서 CORS 함수는 전역 구성에 사용됩니다. @cross_origin을 사용하여 특정 경로의 구성을 구현합니다. 🎜🎜🎜🎜더 많은 관련 무료 학습 권장사항: 🎜🎜🎜python 비디오 튜토리얼🎜🎜🎜🎜
백엔드 개발 파이썬 튜토리얼 Python Flask는 도메인 간 문제를 해결합니다.

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

Sep 30, 2020 pm 05:23 PM
python

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

      본 웹사이트의 성명
      본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

      핫 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에서 모든 것을 잠금 해제하는 방법
      1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

      뜨거운 도구

      메모장++7.3.1

      메모장++7.3.1

      사용하기 쉬운 무료 코드 편집기

      SublimeText3 중국어 버전

      SublimeText3 중국어 버전

      중국어 버전, 사용하기 매우 쉽습니다.

      스튜디오 13.0.1 보내기

      스튜디오 13.0.1 보내기

      강력한 PHP 통합 개발 환경

      드림위버 CS6

      드림위버 CS6

      시각적 웹 개발 도구

      SublimeText3 Mac 버전

      SublimeText3 Mac 버전

      신 수준의 코드 편집 소프트웨어(SublimeText3)

      MySQL은 지불해야합니다 MySQL은 지불해야합니다 Apr 08, 2025 pm 05:36 PM

      MySQL에는 무료 커뮤니티 버전과 유료 엔터프라이즈 버전이 있습니다. 커뮤니티 버전은 무료로 사용 및 수정할 수 있지만 지원은 제한되어 있으며 안정성이 낮은 응용 프로그램에 적합하며 기술 기능이 강합니다. Enterprise Edition은 안정적이고 신뢰할 수있는 고성능 데이터베이스가 필요하고 지원 비용을 기꺼이 지불하는 응용 프로그램에 대한 포괄적 인 상업적 지원을 제공합니다. 버전을 선택할 때 고려 된 요소에는 응용 프로그램 중요도, 예산 책정 및 기술 기술이 포함됩니다. 완벽한 옵션은없고 가장 적합한 옵션 만 있으므로 특정 상황에 따라 신중하게 선택해야합니다.

      hadidb : 파이썬의 가볍고 수평 확장 가능한 데이터베이스 hadidb : 파이썬의 가볍고 수평 확장 가능한 데이터베이스 Apr 08, 2025 pm 06:12 PM

      HADIDB : 가볍고 높은 수준의 확장 가능한 Python 데이터베이스 HadIDB (HADIDB)는 파이썬으로 작성된 경량 데이터베이스이며 확장 수준이 높습니다. PIP 설치를 사용하여 HADIDB 설치 : PIPINSTALLHADIDB 사용자 관리 사용자 만들기 사용자 : createUser () 메소드를 작성하여 새 사용자를 만듭니다. Authentication () 메소드는 사용자의 신원을 인증합니다. Fromhadidb.operationimportuseruser_obj = user ( "admin", "admin") user_obj.

      MySQL Workbench가 Mariadb에 연결할 수 있습니다 MySQL Workbench가 Mariadb에 연결할 수 있습니다 Apr 08, 2025 pm 02:33 PM

      MySQL Workbench는 구성이 올바른 경우 MariadB에 연결할 수 있습니다. 먼저 커넥터 유형으로 "mariadb"를 선택하십시오. 연결 구성에서 호스트, 포트, 사용자, 비밀번호 및 데이터베이스를 올바르게 설정하십시오. 연결을 테스트 할 때는 마리아드 브 서비스가 시작되었는지, 사용자 이름과 비밀번호가 올바른지, 포트 번호가 올바른지, 방화벽이 연결을 허용하는지 및 데이터베이스가 존재하는지 여부를 확인하십시오. 고급 사용에서 연결 풀링 기술을 사용하여 성능을 최적화하십시오. 일반적인 오류에는 불충분 한 권한, 네트워크 연결 문제 등이 포함됩니다. 오류를 디버깅 할 때 오류 정보를 신중하게 분석하고 디버깅 도구를 사용하십시오. 네트워크 구성을 최적화하면 성능이 향상 될 수 있습니다

      MongoDB 데이터베이스 비밀번호를 보는 Navicat의 방법 MongoDB 데이터베이스 비밀번호를 보는 Navicat의 방법 Apr 08, 2025 pm 09:39 PM

      해시 값으로 저장되기 때문에 MongoDB 비밀번호를 Navicat을 통해 직접 보는 것은 불가능합니다. 분실 된 비밀번호 검색 방법 : 1. 비밀번호 재설정; 2. 구성 파일 확인 (해시 값이 포함될 수 있음); 3. 코드를 점검하십시오 (암호 하드 코드 메일).

      MySQL을 해결하는 방법은 로컬 호스트에 연결할 수 없습니다 MySQL을 해결하는 방법은 로컬 호스트에 연결할 수 없습니다 Apr 08, 2025 pm 02:24 PM

      MySQL 연결은 다음과 같은 이유로 인한 것일 수 있습니다. MySQL 서비스가 시작되지 않았고 방화벽이 연결을 가로 채고 포트 번호가 올바르지 않으며 사용자 이름 또는 비밀번호가 올바르지 않으며 My.cnf의 청취 주소가 부적절하게 구성되어 있습니다. 1. MySQL 서비스가 실행 중인지 확인합니다. 2. MySQL이 포트 3306을들을 수 있도록 방화벽 설정을 조정하십시오. 3. 포트 번호가 실제 포트 번호와 일치하는지 확인하십시오. 4. 사용자 이름과 암호가 올바른지 확인하십시오. 5. my.cnf의 바인드 아드 드레스 설정이 올바른지 확인하십시오.

      MySQL은 인터넷이 필요합니까? MySQL은 인터넷이 필요합니까? Apr 08, 2025 pm 02:18 PM

      MySQL은 기본 데이터 저장 및 관리를위한 네트워크 연결없이 실행할 수 있습니다. 그러나 다른 시스템과의 상호 작용, 원격 액세스 또는 복제 및 클러스터링과 같은 고급 기능을 사용하려면 네트워크 연결이 필요합니다. 또한 보안 측정 (예 : 방화벽), 성능 최적화 (올바른 네트워크 연결 선택) 및 데이터 백업은 인터넷에 연결하는 데 중요합니다.

      고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? 고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? Apr 08, 2025 pm 06:03 PM

      MySQL 데이터베이스 성능 최적화 안내서 리소스 집약적 응용 프로그램에서 MySQL 데이터베이스는 중요한 역할을 수행하며 대규모 트랜잭션 관리를 담당합니다. 그러나 응용 프로그램 규모가 확장됨에 따라 데이터베이스 성능 병목 현상은 종종 제약이됩니다. 이 기사는 일련의 효과적인 MySQL 성능 최적화 전략을 탐색하여 응용 프로그램이 고 부하에서 효율적이고 반응이 유지되도록합니다. 실제 사례를 결합하여 인덱싱, 쿼리 최적화, 데이터베이스 설계 및 캐싱과 같은 심층적 인 주요 기술을 설명합니다. 1. 데이터베이스 아키텍처 설계 및 최적화 된 데이터베이스 아키텍처는 MySQL 성능 최적화의 초석입니다. 몇 가지 핵심 원칙은 다음과 같습니다. 올바른 데이터 유형을 선택하고 요구 사항을 충족하는 가장 작은 데이터 유형을 선택하면 저장 공간을 절약 할 수있을뿐만 아니라 데이터 처리 속도를 향상시킬 수 있습니다.

      Amazon Athena와 함께 AWS Glue Crawler를 사용하는 방법 Amazon Athena와 함께 AWS Glue Crawler를 사용하는 방법 Apr 09, 2025 pm 03:09 PM

      데이터 전문가는 다양한 소스에서 많은 양의 데이터를 처리해야합니다. 이것은 데이터 관리 및 분석에 어려움을 겪을 수 있습니다. 다행히도 AWS Glue와 Amazon Athena의 두 가지 AWS 서비스가 도움이 될 수 있습니다.

      See all articles