SQLite3 and web server

Cecil Westerhof Cecil at decebal.nl
Fri Aug 21 11:44:15 CEST 2015

On Friday 21 Aug 2015 09:27 CEST, Chris Angelico wrote:

> On Fri, Aug 21, 2015 at 5:13 PM, Cecil Westerhof <Cecil at decebal.nl> wrote:
>> I know how to work with SQLite. What I do not know how to make a
>> python web-server that accepts a request from the JavaScript code
>> and responds with data from the SQLite3 database.
> The request from JS will be some sort of HTTP transaction. It'll be
> AJAX or similar, and to your web server, it'll simply be another
> page request. (You might be using a method other than GET/POST
> (which are the only two that regular page loads use), but it's still
> a standard HTTP request.) You then respond to that request with data
> that you got from the database.
> Check out this video from PyCon. Its main thrust is "here's why
> websockets are great, and why other technologies are insufficient",
> but the background info is a tidy summary of how the web works.
> https://www.youtube.com/watch?v=u5QT3luWx7w

Interesting, but it does not help me. I need to know how to server
data from SQLite instead of static files.

I understood that CGI is old school and should not be used anymore,
but I tried it anyway. (Because that is the only thing I found.)

I use the following script:
#!/usr/bin/env python3

import http.server
import os
import socketserver
import sys


PORT = 8000
Handler = http.server.CGIHTTPRequestHandler
httpd   = socketserver.TCPServer(('', PORT), Handler)
print('serving at port {0}'.format(PORT))

In cgi-bin I have the script helloTxt.py, which contains:
#!/usr/bin/env python3

print('Content-type: text/plain\n\n')
print ('Hello World!\n')

My static files are handled correctly, but when I enter:
I get:
Exception happened during processing of request from ('', 49380)
Traceback (most recent call last):
  File "/usr/lib64/python3.4/socketserver.py", line 305, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib64/python3.4/socketserver.py", line 331, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib64/python3.4/socketserver.py", line 344, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib64/python3.4/socketserver.py", line 665, in __init__
  File "/usr/lib64/python3.4/http/server.py", line 398, in handle
  File "/usr/lib64/python3.4/http/server.py", line 386, in handle_one_request
  File "/usr/lib64/python3.4/http/server.py", line 677, in do_GET
    f = self.send_head()
  File "/usr/lib64/python3.4/http/server.py", line 961, in send_head
    return self.run_cgi()
  File "/usr/lib64/python3.4/http/server.py", line 1051, in run_cgi
    env['SERVER_NAME'] = self.server.server_name
AttributeError: 'TCPServer' object has no attribute 'server_name'

Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof

More information about the Python-list mailing list