Home Backend Development Python Tutorial Configure multiple subdomain names in Python's Flask framework

Configure multiple subdomain names in Python's Flask framework

Mar 03, 2017 pm 02:21 PM

Flask子域名

一般用于数量比较少的子域名,一个模块对应一个子域名。先看下面一个例子:

modules.py:

from flask import Blueprint

public = Blueprint('public', __name__)

@public.route('/')
def home():
  return 'hello flask'
app.py:

app = Flask(__name__)
app.config['SERVER_NAME'] = 'example.com'
from modules import public
app.register_blueprint(public, subdomain='public')
Copy after login

现在可以通过public.example.com/来访问public模块了。

通配符子域
通配符子域,即通过一个模块来匹配很多个子域名。比如某些网站提供的个性化域名功能,就是这种形式。

先来看段示例代码:

modules.py:

from flask import Blueprint

member = Blueprint('member', __name__)

@member.route('/')
def home():
  return g.subdomain
app.py:

app = Flask(__name__)
app.config['SERVER_NAME'] = 'example.com'
from modules import member
app.register_blueprint(member, subdomain=&#39;<subdomain>&#39;)
Copy after login

这段代码和上一节的第像,不同之处是这里的subdomain使用了动态参数(路由中的URL变量也是这种方式)。我们可以用这个参数在请求回调函数之前利用的组合的url处理器来获取相关的用户。这样我们就可以通过*.example.com的形式来访问member模块了。

下面是为任何Flask或Blueprint对象增加子域名支持的便捷函数:

def add_subdomain_to_global(endpoint, values):
  g.subdomain = values.pop(&#39;subdomain&#39;, None)

def add_subdomain_to_url_params(endpoint, values):
  if not &#39;subdomain&#39; in values:
    values[&#39;subdomain&#39;] = g.subdomain

def add_subdomain_support(app):
  app.url_value_preprocessor(add_subdomain_to_global)
  app.url_defaults(add_subdomain_to_url_params)
Copy after login

然后你可以使用before_request回调函数来处理子域名:

add_subdomain_support(blueprint)

@blueprint.before_request
def add_user_to_global():
  g.user = None
  if g.subdomain:
    g.user = User.query.filter_by(username=g.subdomain).first_or_404()
Copy after login

注:这里的blueprint请改为实际对象。

特别说明:通配符子域调试不是不太方便,需要做泛域名解析才可以。修改hosts文件来指定域名的方法是不可行的(子域名较少时可以逐个添加,子域名多了就不太现实了)。本机调试时,可以安装DNS服务器(比如LINUX BIND服务等),并做好泛域名解析,然后再进行调试。当然使用公网域名和服务器来调试也未尝不可。

PS:
1.如果某个blueprint默认就需要实用a.domain.com,那么在定义blueprint时候:

a=Blueprint(‘a&#39; ,__name__,subdomain=&#39;a&#39;)
Copy after login

这样,该bp下面的所有url routing走的都是a.domain.com/xxx

2.在某个具体的url routing定义时,如果需要实用a.domain.com,那么这么写:

@www.route(‘/hello&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;],subdomain=&#39;a&#39;)
def xxx():
…..
Copy after login

3.我在具体实践中,默认的routing都是走的www,这是在__init__.py中:

app.url_map.default_subdomain=&#39;www&#39;
Copy after login

其实就是设置默认子域名,这样默认不做设置的话,路由走的就是www。
那这个时候如果访问domain.com,即不带www的话,就会报404了,怎么办呢,我是在nginx层面解决这个问题的,在nginx.conf增加一个server:

server {
server_name domain.com;
rewrite ^(.*) http://www.domain.com$1 permanent;
}
Copy after login

更多Python的Flask框架中配置多个子域名相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

See all articles