It is necessary to create a simple one-page website for test purposes. On the page you need to be able to make AJAX requests to the server. Please, tell me how to implement server infrastructure in the simplest and fastest way. It is necessary to take into account that the server will be launched both on a local machine by a non-technical specialist, and on a common test server. There is no special software on the local machine of a non-technical specialist. On the server, apache2 is used, and the environment for django – projects is configured.
1 answer
The easiest way to implement this is to use the built-in python HTTP – server on the local machine and a simple WSGI – application on the server. When creating a project structure, it is necessary to take into account that when working through WSGI, static files are best delivered directly through apache.
The proposed project structure will be as follows.
server.py static/ | - index.html | - m/ | - styles.css | - scripts.js | - img/
In this case, we will be able to work equally with project files. In html / css code, links to static files will look like this.
/m/scripts.js
Apache configuration
<VirtualHost *:80> ServerAdmin webmaster@mysite.ru DocumentRoot "/path/to/my/site/root/" ServerName mysite.ru WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess mysite WSGIProcessGroup mysite WSGIScriptAlias / /path/to/my/site/root/server.py Alias /m/ /path/to/my/site/root/static/m/ <Directory /path/to/my/site/root/static/m/> Order deny,allow Allow from all </Directory> ErrorLog "/var/log/apache2/mysite_error.log" LogLevel warn CustomLog "/var/log/apache2/mysite_warning.log" combined </VirtualHost>
In the configuration file for the server, we showed where our WSGI script is located ( WSGIScriptAlias / /path/to/my/site/root/server.py
). It is proposed to use the same script for the local server. We also added an alias for /m/
( Alias /m/ /path/to/my/site/root/static/m/
). Thus, all that remains is to make the static
folder the working directory for the local server, and apache will automatically handle file links itself.
import SimpleHTTPServer import SocketServer import os import sys PORT = 8000 AJAX_ENPOINT_URL = "/ajax/endpoint" DOCUMENT_ROOT = "/path/to/my/site/root/" # Обработчик локального сервера. class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): # Обрабатываем GET–запрос к серверу. # Если запрос к приходит по известному нам URL, формируем ответ. # Если мы не знаем URL, предлагаем стандартной библиотеки обработать его. def do_GET(self): if self.path == AJAX_ENPOINT_URL: self.send_response(200) self.send_header('Content-type','application/json') self.end_headers() self.wfile.write("My ajax response") return else: SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) if __name__ == "__main__": os.chdir("./static/") httpd = SocketServer.TCPServer(("", PORT), CustomHandler) print "Serving at port", PORT httpd.serve_forever() quit() def get_index(): f = open(DOCUMENT_ROOT +'/static/index.html', 'r') data = f.read() f.close() return data def application(environ, start_response): output = "" status = "200 OK" content_type = "text/plain" path = environ.get('PATH_INFO', None) if path == "/" or path == "index.html": output = get_index() content_type = 'text/html' elif path == AJAX_ENPOINT_URL: content_type = 'application/json' output = "My Ajax response" if output == "": status = "404 Not Found" output = "Not Found" response_headers = [('Content-type', content_type), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]
To start the server on a local machine, just go to the root of the project and execute the command
python server.py
If running to the server, you need to add the apache configuration to the configuration folder and restart it.