♚ \

PayneLi is an expert in data mining, machine learning, and deep learning. PayneLi is an expert in data mining, machine learning, and deep learning.

\

Recently, I used Django to develop a small program and a backend management system that required deploying two different projects into the same service, and then using different domain names to access the different projects. By default, Django only supports single-server access. To implement different domain names, you need to install django-hosts, a third-party extension of Django.

\

This article uses a simple demo to demonstrate, the premise of this article is to have some knowledge of Django, the construction of the project environment and Nginx understanding.

I. Setting up environment and Project:

Anconda is used to manage Python packages, so this article will use Anconda to manage the environment, of course, if you are used to using Virtuallen to manage the environment is no problem. This article is mainly to demonstrate how to complete the construction of a single service to achieve multi-domain access process, does not involve specific business processes.

Since generating a Django project requires downloading the Django package, we will create a basic virtual environment and then use specific commands to generate the project files in the virtual environment.

\

1. Environment construction: applite_web

conda create --name applite_web
Copy the code

Now that you have created the virtual environment applite_web, you need to download some dependency packages. You only need to install Django and Django-hosts separately. \

Copy the code

pip install django  

pip install django-hosts

pip install uwsgi

\

2. Create project applite_web

django-admin.py startproject applite_web
Copy the code

\

3. Create app

# app_1 and app_2 are used to match the url of the applite_web file that hosts. Py is distributed at the same level as django's original urls. # app_1_demo and app_2_demo: Py startApp app_1 create app_2: Django manage.py startApp app_2 create app_1_demo: django manage.py Django manage.py startApp app_1_demo Creates app_2_demo: Django manage.py startApp app_2_demoCopy the code

\

Note 2:

1) The original Django project structure has been adjusted according to the needs of the project

2) The usage of creating four apps will be covered in detail later

\

The following screenshot is to create the Demo project structure of this article, of course, this is a relatively simple project structure, the actual project development, but also need to configure other parameters and files.

2. Configure Django-hosts on applite_web

Once you’ve created your virtual environment and project, the next step is to configure multiple domains in Django. For the sake of convenience, this article only demonstrates 2 domain names, multiple domain names can be added as 2 domain names.

\

1. Add a hosts.py file to the settins.py hierarchy as follows:

from django_hosts import patterns, host

host_patterns = patterns(
       host(r'app1', 'app_1.urls', name='app1'),
       host(r'app2', 'app_2.urls', name='app2'),
          )
Copy the code

\

2. Then add three Settings to the Django Settings configuration file:

  • Add the following to INSTALLED_APPS
INSTALLED_APPS = [
    "django_hosts",
    'app_1',
    'app_2',
    "app_1_demo",
    "app_2_demo",
]
Copy the code

\

  • You need to add two more lines to the top and bottom lines of MIDDLEWARE
MIDDLEWARE = [
    'django_hosts.middleware.HostsRequestMiddleware',
    ......
    'django_hosts.middleware.HostsRequestMiddleware',
]
Copy the code

\

  • Add the following two lines to ROOT_URLCONF
Py file's host_patterns matches ROOT_HOSTCONF = 'applite_web.hosts'. DEFAULT_HOST = 'app1'Copy the code
Copy the code

\

3. Configure THE URL and View. After completing the above two steps, go to the APP folder and write the corresponding URL and view. This article is to demonstrate two domain names, while considering that generally a single project will have multiple modules, so it is necessary to configure two urls respectively. 1. Create urls.py files under app_1 and app_2 respectively and add corresponding urls as follows:

  • The urls.py file for app_1 looks like this:
from django.urls import path, include

urlpatterns = [
    path("app1/", include("app_1_demo.urls"))
]
Copy the code

\

  • The urls.py file for app_2 is shown below
from django.urls import path, include

urlpatterns = [
    path("app2/", include("app_2_demo.urls")),
]
Copy the code

\

**2, app_1_demo and app_2_demo add corresponding URL and views function ** respectively

  • After a successful match in app_1, it jumps directly to the app_1_demo urls and then jumps to the current views function based on the current match

1) First match the route of the app_1_demo urls:

from django.urls import path
from .views import app_1_view

urlpatterns = [
    path("", app_1_view),
]
Copy the code

\

**2) after the urls match, jump to the view function here and return the response **

from django.http.response import HttpResponse

# Create your views here.
def app_1_view(request):
    return HttpResponse("hello i'm app_1")
Copy the code

\

  • Similarly, after app_2 is successfully matched, it will jump directly to app_2_demo urls, and then jump to the current views function based on the current match

    \

1) First match the route of app_2_demo urls as follows:

from django.urls import path, include
from .views import app_2_view

urlpatterns = [
    path("", app_2_view)
]
Copy the code

\

2) After the urls match, jump to the view function here and return the response

from django.http.response import HttpResponse

# Create your views here.
def app_2_view(request):
    return HttpResponse("hello i'm app_2")
Copy the code

\

4. Domain binding and testing

After the previous three steps, you have completed a basic demonstration function. The purpose of this article is to use Nginx to load a single service to realize the access of different domain names in a single service, so in the configuration of UWGI and Nginx parameters, also need to bind domain names.

\

1, here is in the same LAN through two machines to achieve user access:

The host IP address is 192.168.2.17, and the service IP address is 192.168.2.200. In actual production, a real domain name needs to be purchased. Here, as a demonstration, you can achieve access to the service of another machine by binding the IP address of the server on the local machine. Specific modifications are as follows:

Add the following two lines to the file: Cc 192.168.2.200 app1.cc 192.168.2.200 app2.ccCopy the code

\

2. After binding, put the project on the 192.168.2.200 machine to test the current service configuration.

Project placement path is: / home/yxy/payneli/applite_web /

\

  • Enter the app folder and run the project as follows:
Python manage. Py runserver then executes 192.168.2.200:8000Copy the code

\

  • Cc :8000/app1/. If the following information is displayed, the project configuration is successfully bound to the domain name

5. Configure and test UWSGi parameters

After the previous steps are successful, it’s time to configure the parameters for UWSGi. As anyone familiar with Python development should know, the Python manage.py runServer used to run the server during development is only suitable for debugging code at development time, and djangos built-in services are not sufficient for actual project deployment. As a Python server, Uwsgi can not only provide stable services, but also provide a large amount of concurrency, so it is often used in background development.

\

1. Under the project folder, create a UWSGi folder. Go to this folder and create the uwsGi. ini file with the following configuration parameters:

[uwsgi] chdir = # project directory/home/yxy/payneli/applite_web/app / # of the specified project application wsgi - file = applite_web/wsgi. Py # specified file path of the sock Socket = / home/yxy/payneli/applite_web/uwsgi/uwsgi sock number # process workers = 1 Pidfile = / home/yxy/payneli/applite_web/uwsgi/uwsgi pid # designated IP port # nginx load balancing using the socket, uwsgi start the service using HTTP Master =true # Vacuum =true # Remove Unix socket and PID files automatically when service stops Serialize the received content, If possible thunder-lock=true # enable thread enable-threads=true # Set auto-interrupt time harakiri=30 # Set buffer post-buffering=4096 # Set log directory daemonize=/home/yxy/payneli/applite_web/logs/uwsgi.logCopy the code

\

2. After the configuration, run the following command to start the service.

Ini: uwsgi --ini./uwsgi/uwsgi.iniCopy the code

\

Uwsgi.pid uwsgi.sock will be added to the uWSgi folder

\

Then check whether the current service is started successfully:

# the command is ps - ef | grep uwsgiCopy the code

\

When the following figure is displayed, uWSGi has successfully started the project

\

3. Whether the browser test service is normal:

Cc :8000/app1/. If the following information is displayed, the UWSGi configuration is successful

\

6. Nginx configuration and testing

If the previous 5 steps are ok, then congratulations, you just need the last step to complete the demo. Now for the final step, configure the Nginx parameters.

\

1, first install Nginx, this article does not explain the Nginx installation, after all, there are so many online tutorials, you can find a good tutorial to follow the operation can be. /usr/local/ Nginx = /usr/local/ Nginx = /usr/local/ Nginx

/usr/local/nginx/sbin/nginx
Copy the code

\

To check whether Nginx is started successfully, run the following command:

ps -ef|grep nginx
Copy the code

\

If the following figure is displayed, Nginx is successfully started

\

Enter app1.cc in the browser. If the following information is displayed, Nginx is successfully installed

\

2, check the Nginx configuration no problem, is to configure multiple domain names.

  • Comment out the original Nginx configuration server

\

  • The following parameters are added to facilitate the addition of files with two domain names app1.cc and app2.cc

 

  • Add /usr/nginx/conf/ and create a new folder called multihosts. Go to the folder and create app1.cc.conf and app2.cc.conf respectively.

    App1.cc. conf configuration is as follows:

server{ listen 80; Server_name app1.cc; HTML inex.htm index.php; #root /data/www/applite_web/; access_log /usr/local/nginx/logs/app1.log logmain; rewrite_log on; #error_page 404 /404.html; Location / {# include uwsgi_params; # include uwsgi_params; # uWSgi uwsgi_pass 192.168.2.200:8000; # load background services uwsgi_param UWSGI_CHDIR/home/yxy/payneli/applite_web/app /; uwsgi_param UWSGI_SCRIPT applite_web.wsgi; client_max_body_size 35m; uwsgi_send_timeout 1060; uwsgi_connect_timeout 1060; uwsgi_read_timeout 1060; }Copy the code

\

  • App2.cc. conf configuration is as follows:
server{ listen 80; server_name app2.cc; #index index.html inex.htm index.php; #root /home/yxy/www/applite_web/; access_log /usr/local/nginx/logs/app2.log logmain; rewrite_log on; #error_page 404 /404.html; location / { include uwsgi_params; Uwsgi_pass 192.168.2.200:8000; uwsgi_param UWSGI_CHDIR /home/yxy/payneli/applite_web/app/; uwsgi_param UWSGI_SCRIPT applite_web.wsgi; client_max_body_size 35m; uwsgi_send_timeout 1060; uwsgi_connect_timeout 1060; uwsgi_read_timeout 1060; }}Copy the code
Copy the code

\

When using Nginx as a load baler, you need to change the uwsgi.ini parameter HTTP to socket as follows:

# HTTP =192.168.2.200:8000 # HTTP =192.168.2.200:8000 # HTTP =192.168.2.200:8000Copy the code

\

Nginx: Nginx: Nginx: Nginx: Nginx: Nginx: Nginx: Nginx: Nginx: Nginx

Cc and app2.cc if the following information is displayed, the multiple domain names are configured successfully

\

So far, a single service implementing multiple domain access has been demonstrated. Of course, this article is only a simple demo version, and the actual project development process, according to the actual needs of the evaluation, decide whether nginx background load multiple services, or nginx load single service mapping multiple domain names.

\

§ § \

Python Chinese community as a decentralized global technology community, to become the world’s 200000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the Ministry of Public Security, ministry of industry, tsinghua university, Beijing university, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, represented by Google, Microsoft and other government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.

\

The recent hot

\

Build CNN model to crack website captcha \

\

Image recognition with Python (OCR) \

\

Analysis of employment status of Python development in Beijing \

\

Memories of youth in QQ space with Python \

\

Email: [email protected]

\

Please click below to read the original article. ** See all articles in the Python Chinese community at **** **