CherryPy server errors log - cherrypy

Where does the CherryPy server write its error logs to? I have installed CherryPy and fired up the server with python3.2
from cherrypy import wsgiserver
def my_crazy_app(environ, start_response):
status = '200 OK'
response_headers = [("Content-type","text/plain")]
start_response(status, response_headers)
return ['Hello world!']
server = wsgiserver.CherryPyWSGIServer(
('0.0.0.0', 80), my_crazy_app,
server_name='www.cherrypy.example')
server.start()
When I go to the url the page does not load and no errors are printed.

You need to specify the error or access log file name. You can do so in a config file...
[global]
log.error_file = 'Web.log'
log.access_file = 'Access.log'
or in a Python file...
cherrypy.config.update({'log.error_file': 'Web.log',
'log.access_file': 'Access.log'
})
I'm thinking your getting a "Port 80 not free" error. Try changing your port to 8080.
Andrew

Related

How to solve 401 Unauthorized error in Socket.IO Django framework?

I am trying to get the Socket.IO work with my Django server. Here is my setup:
Frontend js:
const socket = io.connect('127.0.0.1:8001');
socket.on('connect', () => {
console.log('socket id: %s\n', socket.id);
});
Django server:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*', logger=True, engineio_logger=True)
#sio.event
def connect(sid, environ, auth):
print('connect ', sid, auth)
static_files = {
'/public': './static',
}
application = socketio.WSGIApp(sio, application, static_files=static_files)
eventlet.wsgi.server(eventlet.listen(('', 8001)), application)
Dependencies
Django==2.2.11
django-cors-headers==3.0.0
eventlet==0.30.0
gunicorn==19.7.1
python-socketio==4.6.1
...
When I run the js, the server will return 401 unauthorized error before reaching the connect function.
Frontend:
GET http://127.0.0.1:8001/socket.io/?EIO=3&transport=polling&t=NYKlRjO 401 (UNAUTHORIZED)
Django server log:
(11053) accepted ('127.0.0.1', 34906)
127.0.0.1 - - [02/Apr/2021 15:39:31] "GET /socket.io/?EIO=3&transport=polling&t=NYKlTB8 HTTP/1.1" 401 253 0.002482
But the weird thing is if I commented out the connect event, everything like other events work just fine:
# #sio.event
# def connect(sid, environ, auth):
# print('connect ', sid, auth)
The Django server is running on the same port 8001. I don't think there is any authentication check on the connect event or on the socket. Anyone knows why if I setup the connect event and the socket suddenly stop working?
It took me hours to figure this out because of the server response code is irrelevant to the issue here.
The problem is, for my case, when the js trying to connect to the socket server, there is no auth argument so the connect function will raise an exception cases the connection to fail, while all exceptions raise from the conncet function will result in 401 unauthorized although it may not be the authorization issue.
The fix is simple, change the connect definition to:
#sio.event
def connect(sid, environ, auth=''):
print('connect ', sid, auth)
will address the issue. Always assing auth token from the frontend js is a good idea as well.

OSError: [Errno 22] Invalid argument for udp connection

The udp server and client on my local pc.
cat server.py
import socket
MAX_BYTES =65535
def server():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10000))
print('Listening at {}'.format(sock.getsockname()))
while True:
data,address = sock.recvfrom(MAX_BYTES)
text = data.decode('ascii')
print('The client at {} says {!r} '.format(address,text))
if __name__ == "__main__":
server()
Bind port 10000 with localhost-127.0.0.1,and listening to the message send from client.
cat client.py
import socket
import time
from datetime import datetime
MAX_BYTES =65535
def client():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10001))
text = 'The time is {}'.format(datetime.now())
data = text.encode('ascii')
while True:
time.sleep(10)
sock.sendto(data,('127.0.0.1',10000))
print('The OS assinged me the address {}'.format(sock.getsockname()))
if __name__ == "__main__":
client()
Run the server.py and client.py on my local pc,server can receive message send from client.
Now i change 127.0.0.1 in the line in client.py with my remote vps_ip.
sock.sendto(data,('127.0.0.1',10000))
into
sock.sendto(data,('remote_ip',10000))
Push server.py into my vps.Start client.py on my local pc,server.py on remote vps,start them all.
In my client,an error info occurs:
File "client.py", line 13, in client
sock.sendto(data,('remote_ip',10000))
OSError: [Errno 22] Invalid argument
How to make remote ip receive message send from my local client pc?
Two things that could be happening:
You're not passing the remote IP correctly. Make sure that your not passing literally 'remote_ip' and replace it with a valid IPv4 IP address string (IE: '192.168.0.100') for the server. (FYI technically on the server you can just put '0.0.0.0' to listen on all IP addresses)
You could still be binding the client to the local address to (127.0.0.1), but setting the destination to a valid external address (192.168.0.100). Remove the socket.bind line of code in the client to test this, you shouldn't need it.
If these both don't work, then add the results of a ping command running on the client and targeting the server.

Error in server-running while acessing web-page

We are assigned to write a simple app including three pages + mainpage that is going to have links to all other pages (content cut for the version here). Below is fully-functional code, that accomplishes all of that. Nevertheless there is an error randomly arising while running server, which, however, does not affect the work of the server at all.
I have tried to look at what is going on with the requests sent to the server and it showed me that periodically instead of one request, server receives two
import socketserver
from server import ThreadedTcpServer
from request import Request
from response import Response
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
print('Connected from: ' + str(self.client_address))
print('==========Request===========')
request = Request(self.rfile)
print(request.request_line + '\n')
response = Response(self.wfile)
response.add_header('Content-Type', 'text/html')
response.add_header('Connection', 'close')
if request.path == '/':
...
response.send()
ThreadedTcpServer.allow_reuse_address = True
server = ThreadedTcpServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
server.server_close()
In the log of the server I expect to see only request_lines and print of connection info,but sometimes instead of one request it shows two from different client_addresses and two arising exceptions like:
Connected from: ('127.0.0.1', 34962)
==========Request===========
GET /three HTTP/1.1
Connected from: ('127.0.0.1', 34966)
==========Request===========
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34966)
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34962)
and huge traceback starting from socketserver module and ending up in my request class where it cannot parse request_line.

How can I create a TCP server using Python 3?

How can I create a TCP server in python3 which will return all the files in the current directory?
You can use the socketserver library, this will serve the current working directory.
Here is the Server code
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
# here you can do self.request.sendall(use the os library and display the ls command)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
And here is the client side
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
You should then get an output like
Server:
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'
Client:
$ python TCPClient.py hello world with TCP
Sent: hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent: python is nice
Received: PYTHON IS NICE
You can then just use this code to send the current directory list
You can use socketserver which will serve the current working directory.
import socketserver # import socketserver preinstalled module
import http.server
httpd = socketserver.TCPServer(("127.0.0.1", 9000), http.server.SimpleHTTPRequestHandler)
httpd.serve_forever()

How to stop WsgiServer in Linux

I am a newbee in cherrypy.
I just tried with a sample program of wsgiserver.The program is as follows
from cherrypy import wsgiserver
def my_crazy_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!']
server = wsgiserver.CherryPyWSGIServer(
('127.0.0.1', 8080), my_crazy_app,
server_name='localhost')
server.start()
I got the output Hello world successfully,
but the problem is when i hit Ctrl-c on the terminal to stop the server, its not getting stopped. How to do it?
IIRC, the wsgiserver itself is not associated to any signal and therefore doesn't respect the SIGINT interruption.
Only the higher level CherryPy engine will provide that. If you can't use it, you probably want to
install a handler using the Python signal module.
Well, something along those lines will do the job:
import signal
from cherrypy import wsgiserver
def my_crazy_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!']
server = wsgiserver.CherryPyWSGIServer( ('127.0.0.1', 8080), my_crazy_app, server_name='localhost')
def stop_server(*args, **kwargs):
server.stop()
signal.signal(signal.SIGINT, stop_server)
server.start()

Resources