table of Contents:
Upgrade Python on CentOS
Install easy_install and pip
uwsgi installation and testing
Django installation and testing
Connect uwsgi and Django
Nginx installation and testing
Connect uwsgi and nginx
Connect uwsgi with Django and nginx
uwsgi ini
mysql installation settings
python3 Django mysql connection and test
Quickly build blog test
Pycharm development
If you just want to learn Django development, just use Django's own development server.
1. Upgrade Python on CentOS
The system used is CentOS 6.4, the python version on it is 2.6, and the version supported by Django is 2.7+, and considering that the web language uses UTF-8, and the python3+ default characters have become Unicode, so choose the python3 version. Don't know right or wrong.
I installed python 4 times before and after, every time I encountered the problem of missing a certain module when compiling, I had to install another module and recompile. These modules are,
yum install zlib zlib-devel
yum install bzip2 bzip2-devel
yum install openssl openssl-devel
yum install sqlite-devel
Tar it after the installation, what I want to say here is that because there is a built-in pyhton, so we install to a new directory, do not overwrite.
. /configure --prefix=/usr/local/python3.6&& make && make install
Under /usr/bin, we can see that there are python, python2, python2.6, which are actually a file, we put our own ln in the past,
ln -s /usr/local/python3.6/bin/python3.6/usr/bin/python
python -V
You can see that the version has changed. But at this time I used yum and found an error, alas,
vim /usr/bin/yum
#! /usr/bin/python to#!/usr/bin/python2.6
That's it, python installation under CentOS comes to an end.
(Note: If you don’t want to do ln -s links frequently in the future, set /usr/local/python3.3/bin as an environment variable and make up your own network.)
2. Install easy_install and pip
It may be easy for you, but it’s too difficult for me,
wget https://bootstrap.pypa.io/ez_setup.py
python ez_setup.py
ln -s /usr/local/python3.6/bin/easy_install /usr/bin/easy_install
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
python get-pip.py
As mentioned in the tutorial, you should be able to execute pip -V directly after the installation is complete. As a result, I can’t find the command, or pip was not automatically set as a command. I can’t find pip when I go to the python directory. File, which file should be ln, so after a long time unsuccessful, this method was adopted,
( Note: If you want yum to install pip, you need to install EPEL first, see http://xmodulo.com/how-to-set-up-epel-repository-on-centos.html for details, select the corresponding version, and the corresponding solution. Sometimes the configuration under windows is simple, and sometimes linux must be selected. )
yum install python-pip
pip -V
Then you report an error. People always let the pursuit of reality get lower and lower. It's too happy to report an error, indicating that this order has already been issued. Checking the error is a version conflict, because we have installed 1.5.6 above (currently the latest), yum installed 1.3, so I checked the pip file, out of instinct
Change 1.3. Jiquan to 1.5.6,
vim /usr/bin/pip
After modification:
#! /usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT:'pip==1.5.6','console_scripts','pip'
__ requires__ ='pip==1.5.6'import sys
from pkg_resources import load_entry_point
if __name__ =='__main__':
sys.exit(load_entry_point('pip==1.5.6','console_scripts','pip')())
Smartly, I backed up and then yum removed python-pip. Sure enough, pip was gone. I restored the backup and pip was finally used normally. It's hard!
After working on it for a long time, I finally came to the topic. Why did you choose uwsgi? It’s because the mod_wsgi configuration of Apache is too difficult. The information found on the Internet, each person has his own steps, and each person has his own path. Like, it’s not like learning that. Is it okay to only learn from one person? If you encounter problems, you still have to go to others. After all, everyone encounters different problems. In this day-long start: encounter problems, find problems, and solve problems, uwsgi was found in goto start, which is known as a cure for various stubborn diseases of mod_wsgi, and it is also matched with nginx, so let's build this.
pip install uwgsi
ln -s /usr/local/python3.6/bin/uwsgi /usr/bin/uwsgi
Let's test it now,
vim test.py
# test.py
def application(env, start_response):start_response('200 OK',[('Content-Type','text/html')])return[b"Hello World"] # python3
# return["Hello World"] # python2
uwsgi --http :8001--wsgi-file test.py
Visit http://localhost:8001 at this time to see Hello World, which is successful.
(Supplement: Success is not easy. Why are the tutorials everywhere writing return "xxxxx", but the web page has no output. I found the official website and found that I need to add b. The reason is of course that the version is different. It doesn't matter whether [] is added or not. But in python3, because the characters are unicode by default, they must be encoded. The b"xxx" can also be changed to "xxx".encode('utf-8'), but #-- before the text coding: UTF-8 --but it doesn't work.
In python3, text is always Unicode, represented by str type, and binary data is represented by bytes type.
uwsgi -s :8001 -wsgi-file test.py, invalid request block size: 21573 (max 4096)...skip will appear when accessing, because the usgi parameter -s means that the communication port is provided in socket mode, and the default protocol is tcp. When accessing uwsgi via nginx, it doesn't matter. )
4. Django installation and testing
The sqlite module is used in the test here.
pip install django
cd /usr/local/python3.6/bin/
python django-admin.py startproject myproject
cd myproject
python manage.py runserver 0.0.0.0:8002
Open the browser and visit http://localhost:8002 to display It worked!.., success. Now I’m smarter, I’ll read a few more tutorials to get in touch, and it’s not easy to make errors.
5. Connect uwsgi and Django
Don't see some tutorials, just follow to create a django_wsgi, now the version is not needed, just myproject.wsgi can be.
uwsgi --http :8004--chdir /home/wwwroot/default/myproject --module myproject.wsgi
Success can be seen in It worked!.
6. nginx installation and testing
yum install nginx
service nginx start
The browser visits localhost, you can see Welcome to nginx on EPEL!, success. But don't use this method, we don't know the related configuration of its automatic installation, so you must choose source installation. Because of my previous greed and simplicity, I encountered many permission problems later, and finally reinstalled it, but many of the following chapters were carried out in the above configuration mode, and I was too lazy to modify it.
Before this, there are quite a few environments to install, especially Pcre.
yum install patch make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-libs autoconf kernel-devel libjpeg libjpeg-devel libpng libpng-devel libpng10 libpng10-devel gd gd-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel vim-minimal nano fonts-chinese gettext gettext-devel ncurses-devel gmp-devel pspell-devel unzip libcap diffutils
wget http://soft.vpser.net/web/pcre/pcre-8.30.tar.gz
tar it configure make make install
groupadd www
useradd -s /sbin/nologin -g www www
wget http://soft.vpser.net/web/nginx/nginx-1.6.2.tar.gz
tar it
. /configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-ipv6
make && make install
After the installation is complete, there are 2 startup methods:
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
/usr/local/nginx/sbin/nginx
I don't know much, so I use the first one because I will reread the configuration file every time. At this time, it prompts that libpcre.so.1 cannot be found, so we can
find /-name "libpcre.so.*"
You will find libpcre.so.0.0.1 under /lib64, 32-bit is under /lib, let’s do ln,
ln -s /lib64/libpcre.so.0.0.1/lib64/libpcre.so.1
Then start nginx again, no error, open the browser to visit http://localhost, you can see Welcome to nginx on EPEL!, success.
7. Connect uwsgi and nginx
Nginx user permissions are very worrying, but few people on the Internet have encountered my problem. At first, I wanted to change the log path. It can be seen that the user is nginx in nginx.conf. I even changed the permissions of a folder to a+rwx, the owner Change to nginx still permission denied. Also, /var/run/nginx.pid cannot be found every time it is started, so service nginx start cannot be used. Finally, the start method is changed to /usr/sbin/nginx -c /etc/nginx/nginx.conf.
At the beginning, I chose to write myproject.conf in the conf.d directory, but in order to avoid permission denied everywhere, based on the principle of minimal changes, only modify nginx.conf as follows:
vim /etc/nginx/nginx.conf
On http{}Add as follows:
upstream django {
server 127.0.0.1:8001; # for a web port socket
}
server {
listen 8000;
server_name xqlm.com; # substitute your machine's IP address or FQDN
charset utf-8;
client_max_body_size 75M; # adjust to taste
# location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
#}
# location /static{
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
#}
# Finally, send all non-media requests to the Django server.
location /{
root /Your project directory/myproject;
uwsgi_pass django;
include uwsgi_params; # the uwsgi_params file you installed
}}
upstream django {
** server 127.0.0.1:8001; # for a web port socket**
** }**
location / {
root /your project directory/myproject;
** uwsgi_pass django;**
** include uwsgi_params; # the uwsgi_params file you installed**
** }**
(important)
After the modification is completed,
uwsgi --socket :8001--wsgi-file test.py
When the browser visits http://localhost:8000, Hello world appears! To indicate success. Here it is necessary to explain the relationship between these ports. The user's access is 8000, which corresponds to the sever listen in nginx.conf, and then nginx will relay this information to django 8001 in nginx.conf, which is to listen when the uwsgi command is started Port. Then, can’t it be forwarded directly to uwsgi? Why do we need to insert nginx in the middle? I had to use online answers to prevaricate "UWSGI alone is not enough. In the actual deployment environment, Nginx is an indispensable tool. Nginx has excellent static content processing capabilities, and then forwards dynamic content to the uWSGI server. A very good client response can be achieved.". In the server above, you will find the commented out location /static and /media, which represent static content and dynamic content, respectively, but now we are an empty project, we don't need it, we will talk about it later.
8. Connect uwsgi with Django and nginx
uwsgi --socket :8001--module myproject.wsgi
(If there is a permisson problem, add --chmod-socket=664 or 666 as appropriate. It is usually caused by using mysite.sock, and the designated port will not.)
The previous steps are tested and every step is correct. There should be no problem by now. Directly visit http://localhost:8000 in the browser, and it is now It worked!
9. uwsgi ini
Do you feel that it is inconvenient for uwsgi to follow a long list of paths every time, then write an ini file, xml is also possible, here only the ini version is given,
vim myproject_uwsgi.ini
# mysite_uwsgi.ini file
[ uwsgi]
# Django-related settings
# the base directory(full path)
chdir =/home/wwwroot/default/myproject
# Django's wsgi file
module = myproject.wsgi
# the virtualenv(full path)
# home =/path/to/virtualenv
# process-related settings
# master
master =true
# maximum number of worker processes
processes =10
# the socket(use the full path to be safe)
# socket =/path/to/your/project/mysite.sock
socket =:8001
# ... with appropriate permissions - may be needed
# chmod-socket =664
# clear environment on exit
vacuum =true
The above is from the official website commonly used and very complete configuration, you can adjust yourself according to your needs. Now just start as follows,
uwsgi --ini myproject_uwsgi.ini
Browser visits 8000, It worked!.
10. mysql installation settings
Not much to say about the installation of mysql,
yum install mysql mysql-devel mysql-server
/etc/rc.d/init.d/mysqld start
/usr/bin/mysqladmin -u root password yourpassword
Here we create a new user for django to use.
mysql -u root -p
mysql> create database myprojectdb;
mysql> use mysql;
mysql> insert into user(Host,User,Password)values('localhost','niger',password('niger'));
mysql> flush privileges;
mysql> grant all privileges on myprojectdb.* to 'niger'@'localhost' identified by 'niger';
11. python3 Django mysql connection and test
First install the connection module of python and mysql, currently python3, I chose mysql-connector-python, and then set the settings.py file of django in the myproject directory. I really can’t find what I’m looking for on Baidu. Google it. Solved easily.
pip install --allow-all-external mysql-connector-python
vim myproject/settings.py
DATABASES ={'default':{'ENGINE':'mysql.connector.django','NAME':'myprojectdb','USER':'niger','PASSWORD':'niger',}}
The database can be set as above, engine is the django module under the mysql.connector we installed, and the other names will know the meaning. Now let’s test whether it is successful,
python manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, admin, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
As shown above, the normal operation (the first time you run will create an administrative user, remember), check the database as follows,
mysql> use myprojectdb;
mysql> show tables;+----------------------------+| Tables_in_myprojectdb |+----------------------------+| auth_group || auth_group_permissions || auth_permission || auth_user || auth_user_groups || auth_user_user_permissions || django_admin_log || django_content_type || django_migrations || django_session |+----------------------------+10 rows inset(0.00 sec)
12. Build a blog quickly
We use django's built-in admin backend to quickly build a blog. As for the meaning of each sentence of code, you will learn more slowly after writing it.
python manage.py startapp blog
We found that there is a blog folder in the myproject directory, enter and modify the models.py in it,
vim models.py
from django.db import models
# Create your models here.classBlogsPost(models.Model):
title = models.CharField(max_length =150)
body = models.TextField()
tiemstamp = models.DateTimeField()
Create the BlogsPost class, inherit the django.db.models.Model parent class, define three variables, title (blog title), body (blog body), tiemstamp (blog creation time) (note that I wrote time as tiem here, and it will continue to follow Go wrong.)
We have to remember the directory structure of django, now go back to myproject/myproject/settings.py, add our app: blog,
vim settings.py
# Application definition
INSTALLED_APPS =('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','blog',)
Look at myproject/myproject/urls.py again, as follows, the admin item must exist,
urlpatterns =patterns('',
# Examples:
# url(r'^$','mysite.views.home', name='home'),
# url(r'^blog/',include('blog.urls')),url(r'^admin/',include(admin.site.urls)),)
Go back to blog/models.py, then add the data to the admin backend and change accordingly
vim models.py
from django.db import models
from django.contrib import admin
# Create your models here.classBlogsPost(models.Model):
title = models.CharField(max_length =150)
body = models.TextField()
timestamp = models.DateTimeField()
admin.site.register(BlogsPost)
Remember that we have initialized the database, and we need to initialize it again after the corresponding changes.
python manage.py makemigrations
python manage.py migrate
Now the database has been successfully changed.
Next, start the website (uwsgi -int myproject_uwsgi.ini, this command will not be attached later, of course, you must ensure that nginx is running.) Visit http://localhost:8000/admin/, you can see the login window Django administration, username, password, log in, how to log in, remember the user we created, just log in.
If there is a style, skip, if not, solve:
Right-click to review the element or firebug, transfer to the console window, refresh the page, and find a css error, click it to see that the path cannot be found, so no style is loaded. When we check the error, we visit the style under localhost:8000/static/admin/css and check various information. Now our static is used. Create a new static under myproject, then set up nginx, and transfer the css code (ask others to know that it is in the django directory),
mkdir static
vim /etc/nginx/nginx.conf
Release static comments and modify
location /static{
alias /Your project path/myproject/static; # your Django project's static files - amend as required
}
find /-name django
/usr/share/doc/python-mako-0.3.4/examples/bench/django
/usr/lib/python2.6/site-packages/mysql/connector/django
/usr/local/python3.3/lib/python3.3/site-packages/mysql/connector/django
/usr/local/python3.3/lib/python3.3/site-packages/django
/root/download/mysql-connector-python-2.0.2/lib/mysql/connector/django
/root/download/mysql-connector-python-2.0.2/build/lib/mysql/connector/django
Find the match from the results, the answer is obvious, we go to copy the files in the django directory to our project, you will find that they are completely corresponding,
[ root@localhost myproject]# cp -rf /usr/local/python3.3/lib/python3.3/site-packages/django/contrib/admin/static/admin/ static/
Take a look at the relevant directory structure. At this time we restart nginx, start the website,
/etc/rc.d/init.d/nginx stop
/usr/sbin/nginx -c /etc/nginx/nginx.conf
Why do I want to stop and start it like this? Because even if I change the user in nginx.conf to root, there are still various permission denied, but this does not report an error. At this time, the visible style of the visited website is loaded normally. )
After logging in, we write a blog,
What did you find, title, body, tiemstamp (haha, I wrote it wrong intentionally to show that this is what I wrote in the program), these 3 variables are defined in class BlogsPost, aren't they? Click save after writing, it will prompt The blogs post "BlogsPost object" was added successfully. How, did you find a corresponding relationship?
But you are like this, every time the BlogsPost object is displayed, it’s not good, how do you know which post it is?
models.py,from django.db import models
from django.contrib import admin
# Create your models here.classBlogsPost(models.Model):
title = models.CharField(max_length =150)
body = models.TextField()
tiemstamp = models.DateTimeField()classBlogPostAdmin(admin.ModelAdmin):
list_display =('title','tiemstamp')
admin.site.register(BlogsPost,BlogPostAdmin)
Pay attention to every change in the code. After restarting the website, we will come to the same location on the website again.
so, the wrong tiemstamp explains everything. We are done with the simple backend, now it's time to see how our frontend is.
From the perspective of Django, a page has three typical components:
A template: The template is responsible for displaying the information passed in.
A view: The view is responsible for obtaining the information that needs to be displayed from the database.
A URL pattern: It is responsible for matching the received request with your view function, and sometimes passes some parameters to the view.
Create template
Create a templates directory under the blog project, and create a template file archive.html in the directory with the following content:
{ %for post in posts %}<h2>{{ post.title }}</h2><p>{{ post.tiemstamp }}</p><p>{{ post.body }}</p>{% endfor%}
Set the template path, open the myproject/myproject/settings.py file, and add the template path at the bottom of the file:
# template
TEMPLATE_DIRS=('/Your project path/myproject/blog/templates',)
Create view function
Open myproject/blog/views.py file:
from django.shortcuts import render
from django.template import loader,Context
from django.http import HttpResponse
from blog.models import BlogsPost
# Create your views here.
def archive(request):
posts = BlogsPost.objects.all()
t = loader.get_template("archive.html")
c =Context({'posts':posts})returnHttpResponse(t.render(c))
posts = BlogPost.objects.all(): Get the BlogPost object owned by the database
t = loader.get_template(“archive.html”): Load template
c =Context({‘posts’:posts}): The rendering data of the template is provided by a dictionary object Context, here is a pair of key-value pairs.
Create blog URL pattern
In myproject/urls.Add the blog url in the py file:
urlpatterns =patterns('',
# Examples:
# url(r'^$','mysite.views.home', name='home'),url(r'^blog/',include('blog.urls')),url(r'^admin/',include(admin.site.urls)),)
In myproject/blog/Create urls under the directory.py file:
from django.conf.urls import*from blog.views import archive
urlpatterns =patterns('',url(r'^$',archive),)
The reason why the urls.py file is created under the blog application is to reduce the coupling. In this way, the myproject/urls.py file is for the url of each project. Restart the website, visit http://localhost:8000/blog/, now you can see the simplest page.
Do you think the page is a bit monotonous, how to adjust it? This is about adding styles.
(The css files are unified under static/admin/css/, just embed them here.)
Add style
In myproject/blog/Create base in the templates directory.html template:
< html><style type="text/css">
body{color:#efd;background:#453;padding:0 5em;margin:0}
h1{padding:2em 1em;background:#675}
h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
p{margin:1em 0}</style><body><h1>Niger blog</h1><h3>From Team Fith4_D3vil</h3>{% block content %}{% endblock %}</body></html>
Modify the archive.html template so that it references the base.html template and its "content" block.
{ %extends"base.html"%}{% block content %}{%for post in posts %}<h2>{{ post.title }}</h2><p>{{ post.tiemstamp | date:"1,F jS"}}</p><p>{{ post.body }}</p>{% endfor %}{% endblock %}
Refresh the page again, you will see a different style.
13. pycharm development
Why is it necessary to build such a complex environment above? It is because it is a website publishing environment. For django developers, everything done above is absolutely unnecessary. Only one pycharm is needed. Now pycharm 4.0 integrates django development. No matter under windows or linux, you only need to install python, install django (not even needed, pycharm will automatically install it for you), open pycharm, the default page is to create a new project, select django , Input the project name and app name. The entire django framework is built automatically and can be run directly. Very convenient.
Recommended Posts