Django + Apache + Raspberry Pi builds an intranet public account server, djangoapache
As a matter of fact, when I opened the public account development platform, I wanted to get my own public account server. I had no idea about how to build and develop web servers. I just registered a developer account and didn't take any action, procrastination.
The year before, I started to access python and opened the door to the magical world. I used to write programs in C, C ++. Developing a program is like installing a machine with strict instructions, step by step. Developed Using python, especially
How can I use my own assistant program? It is like flying in the air, the sky is wide, and Ren Er plays it. I will not repeat the highlights of python here. I just learned a little bit about it. I also want to learn more about it later and continue to work hard.
When I first learned python, I read "Basic python tutorial", which is a good book for me. Chapter 15th describes python web development, you only need simple code to build a simple server and understand the python
The network framework Django later began to read the Django Web Development Guide. In addition, I had some requirements and wanted to customize my public account to provide specific functions for myself, the idea of using Django to set up its own public account server is the same.
It is relatively simple to build a web server with Django and Apache. The Django Web Development Guide provides a reference to this website.
http://www.ziqiangxuetang.com/django/django-deploy.html
This website focuses on Django development. from the beginning to the practice, the author spoke very well. We recommend that you set Django Debug to True (True by default) during the development phase. In this way, you can see the error in the browser when an error occurs on the Access Server,
Of course, in linux, you can view/var/log/apache2/error. log to view error logs.
Generally, servers are not shut down. For me, it seems a waste of power to keep a desktop computer on, because the service is only provided to individuals, and I cannot buy an ECS instance online, there is an idle Raspberry pi second generation. I want to build the server on the pi.
Power supply with a cell phone charger.
To build an intranet server, the main problem is how to make the Internet can access the Intranet at home, I use a peanut shell (http://hsk.oray.com/) to register an account, it will provide a dynamic domain name for free, the TP_Link router is used at home. In the "Dynamic DNS" settings
Enter the registered account and password, and log on. Normally, the connection is successful. The following domain name information can be used as the domain name of your server. The next step is to configure the port number for Internet access to the Intranet. You can configure the forwarding rule of the router for ing.
The above IP address is the IP address of the Intranet server. The server port number is the port number for Internet access, and the internal port number is the port number mapped to the Intranet server listener, in this way, the Internet can access the Intranet server through the domain name. You can test the access by adding a port number to the browser, as shown in figure
Http://xxx.xicp.net/:443/
The server access configuration is basically the same. The next step is to add the server information to the public account development platform. In your own development account, the Development --> basic configuration, fill in the server configuration URL and fill in the above domain name http://xxx.xicp.net (this will be modified below ),
Token (Token). You can enter either of them at will, and enter the same Token on the server side. In the message encryption and decryption mode, enter the plaintext mode in the development phase and submit the Token, show URl access Timeout !!! Here is the first obstacle. I didn't understand why the access timed out at the beginning, because I checked other people's tutorials,
This configuration is all correct, and it is good to access the server through a browser. When something goes wrong, don't worry about finding information online. first think about it, check the configuration steps and see the official development documentation. Finally, we can see that the public account platform supports two port numbers 80 and 443. If port 80 is mapped to the vro,
It will prompt that port 80 is occupied by China Telecom. No way, you can only map port 443. This requires apache ssl access, because port 443 is the corresponding https access.
Set up https access on apache (sharer on Xie Network ):
1. sudo a2enmod ssl
2. sudo apt-get install openssl // install openssl (if openssl has been installed, you do not need to install it. It should have been installed on it)
3. openssl genrsa-des3-out server. key 1024 // when creating a CA signature, the system prompts you to enter the password. You need to enter the password when starting the server later.
4. openssl req-new-key server. key-out server. csr // create a CSR
5. openssl x509-req-days 365-in server. csr-signkey server. key-out server. crt // issue your own certificate
6. sudo cp server. crt/etc/ssl/certs // copy the file to the ssl directory.
7. sudo cp server. key/etc/ssl/private
Then, in the apache server configuration, you need to add something. In the/etc/apache2/sites-available/directory, there is my previous apache configuration web. conf, which is created by yourself,
My configuration is as follows:
<VirtualHost *: 443> # change it to 443
ServerName you.xicp.net # Your server Domain Name
ServerAlias you.xicp.net
ServerAdmin admin
SSLEngine On
SSLOptions + StrictRequire
SSLCertificateFile/etc/ssl/certs/server. crt
SSLCertificateKeyFile/etc/ssl/private/server. key
# The following configuration is related to your Django project. The configuration instructions refer to the http://www.ziqiangxuetang.com/django/django-deploy.html
Alias/media // home/pi/project/media/
Alias/static // home/pi/project/static/
<Directory/home/pi/project/media>
Require all granted
</Directory>
<Directory/home/pi/project/static>
Require all granted
</Directory>
WSGIScriptAlias // home/pi/project/wsgi. py
<Directory/home/pi/project/app>
<Files wsgi. py>
Require all granted
</Files>
</Directory>
</VirtualHost>
The red is the content added by configuring https access.
Then
Sudo a2ensite web. conf # Make your configuration take effect
Sudo/etc/init. d/apache2 restart # After the apache server is restarted and the apache server is restarted, you will be asked to enter the password, that is, the password you entered when creating the CA signature at the beginning
Add url access in Django project code
url(r'^$',comm_view.index),
Comm_view.index is your own view access function. My code is as follows:
#coding=utf-8from django.shortcuts import renderfrom django.http import HttpResponse# Create your views here.import hashlibimport jsonfrom django.utils.encoding import smart_strfrom django.views.decorators.csrf import csrf_exemptWX_TOKEN = "yourtoken"@csrf_exemptdef index(request): print("wx request") if request.method == "GET": signature = request.GET.get("signature",None) timestamp = request.GET.get("timestamp",None) nonce = request.GET.get("nonce",None) echostr = request.GET.get("echostr",None) token = WX_TOKEN tmp_list =[token,timestamp,nonce] tmp_list.sort() tmp_str = "%s%s%s" % tuple(tmp_list) tmp_str = hashlib.sha1(tmp_str.encode("unicode_escape")).hexdigest() if tmp_str == signature: return HttpResponse(echostr) else:return HttpResponse("sucess")
Go to the public development platform to configure Server Configuration, URL at this time to change to https://xxx.xicp.net, other configuration unchanged, submit, the server is working normally, it will prompt success !!!. Click "enable" on the side of "modify configuration.
In this way, the public account configuration is complete.
Return to the code above. The code above shows a "GET" request, which is verified by the Public Account accessing our server. If the subscriber submits a message to our public account, the server will POST the message to our server.
It is to process the POST request and return the result to the public account server and then display it to the user.
At the beginning, I wrote the code like this (connecting to the Code)
elif request.method == "POST": HttpResponse("ok,hello")
During the test, the system prompts "this public account cannot provide services for the moment. Please try again later". However, it is normal to access the account using a browser. I didn't even understand what I provided using the development platform, I can only continue to read the development documentation. The development documentation of the public account is well written (Thank you very much). The example given by the document is to parse the xml when receiving the document and form the xml format when returning the document, is it necessary to make up the xml format document, with the example provided by the development documentation (https://mp.weixin.qq.com/wiki? T = resource/res_main & id = mp1471_1__58yv5 & token = & lang = zh_CN). The returned result is in xml format. Try again !! Of course it won't be successful once ~~, In the middle, ToUserName and FromUserName are assigned to the returned ToUserName and FromUserName, resulting in the normal response when debugging with the development platform tool (http://mp.weixin.qq.com/debug, however, sending messages with your own number still failed. After carefully checking the code, we found that the ToUserName assigned to the response message was FromUserName, in this way, the public account is not chaotic. After mutual adjustment, it is finally successful. Looking at the response to "OK KO", although it is just a simple sentence, it is still a deep sense of satisfaction, which may be a small satisfaction of programmers.
Writing this record is a note of this process, which is used for future viewing. The second is to sort out the information found on the internet and some of your own experiences during the building process, I hope to provide some help to those who have the same requirements. Now, your own server is ready. Use the powerful platform to customize your own services!