cherrypy two servers different ports - python

I want to run 2 servers of cherry py on different ports and with a different application.
I manage to run them both, but how do i connect between the app's and the servers ?
I want to be able to go to
http://127.0.0.1:3141/
and get server1
and to
http://127.0.0.1:3145/
and get server2
cherrypy docs example for multiple servers is not good enough for me to understand how to do this.
here it is Multiple servers/ports
my code
import cherrypy
class App1(object):
#cherrypy.expose
def index(self):
return ('server1')
class App2(object):
#cherrypy.expose
def index(self):
return ('server2')
cherrypy.server.unsubscribe()
server1 = cherrypy._cpserver.Server()
server1.socket_port=3141
server1._socket_host="127.0.0.1"
server1.thread_pool=2
server1.subscribe()
server2 = cherrypy._cpserver.Server()
server2.socket_port=3145
server2._socket_host="127.0.0.1"
server2.thread_pool=2
server2.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()

If your apps need to (or can) be served from different paths (e. g. http://127.0.0.1:3141/app1 and http://127.0.0.1:3145/app2), just use tree.mount() for each app. If both apps must be served from the root path, look at VirtualHost for an idea.

After tweaking for a while I was not able to mount each app to a specific port.
The behavior was that each port was responding to each app, so I added a tool to filter port on each app as shown in the example below:
import cherrypy
from cherrypy._cpserver import Server
#cherrypy.tools.register('before_handler')
def port_filter():
if cherrypy.request.app.root.request_port != cherrypy.request.local.port:
raise cherrypy.NotFound()
class App1(object):
def __init__(self, request_port):
self.request_port = request_port
#cherrypy.expose
#cherrypy.tools.port_filter()
def index(self):
return "Hello world from app1"
class App2(object):
def __init__(self, request_port):
self.request_port = request_port
#cherrypy.expose
#cherrypy.tools.port_filter()
def index(self):
return "Hello world from app2"
class MyServer(Server):
def __init__(self, host, port, thread_pool=10):
Server.__init__(self)
self.socket_port = port
self._socket_host = host
self.thread_pool = thread_pool
self.subscribe()
if __name__ == '__main__':
# Unsubscribe default server
cherrypy.server.unsubscribe()
# Setup server for each port
MyServer(host='0.0.0.0', port=80)
MyServer(host='0.0.0.0', port=8080)
# Mount applications to specific port
cherrypy.tree.mount(App1(80), "/app1")
cherrypy.tree.mount(App2(8080), "/app2")
# Start!
cherrypy.engine.start()
cherrypy.engine.block()

I think you need two different directory. In each directory/app you put a config file for the app.
For example i have something like this:
[global]
server.socket_host = "ip_address"
server.socket_port = 8080
server.thread_pool = 10
[/]
tools.staticdir.root = "/path/to/your/app"
tools.encode.on = True
tools.decode.on = True
Have a look here

Related

How to specify the listening server instances using cherrypy tree.mount?

Let us create an application server and an admin server. Assume that fusionListener and adminListener contain the application and admin logic we want to expose.
from cherrypy._cpserver import Server
fserver = Server()
fserver.socket_port = 10000
fserver.subscribe()
aserver = Server()
aserver.socket_port = 10001
aserver.subscribe()
And then to start them:
cherrypy.engine.start()
cherrypy.engine.block()
The tree.mount parameters ask for:
the code/ business logic as the first parameter
listening url
config parameters
Here is how that looks for the above servers:
cherrypy.tree.mount(fusionListener, r"/fusion.*",fusionConf)
cherrypy.tree.mount(adminListener, r"/admin.*",adminConf)
But where is the parameter for the server itself - which includes the port being listened to?
This is not a well supported case for CherryPy.
The application selection (cherrypy.tree is basically a map of /path -> App) is done before the request dispatch and... long story short, you could use cherrypy.dispatch.VirtualHost and map you sub applications under a main one (that will route depending on the hostname (which the port can be part of). For the listening on multiple ports, can be done, but again this is a very custom arrangement.
I hope this example is illustrative of a possible way to make such feat:
import cherrypy
from cherrypy import dispatch
from cherrypy._cpserver import Server
class AppOne:
#cherrypy.expose
def default(self):
return "DEFAULT from app ONE!"
#cherrypy.expose
def foo(self):
return "FOO from app ONE"
class AppTwo:
#cherrypy.expose
def default(self):
return "DEFAULT from app TWO!"
#cherrypy.expose
def foo(self):
return "FOO from app TWO"
class Root:
def __init__(self):
self.one = AppOne()
self.two = AppTwo()
def bind_two_servers(app_one_port, app_two_port):
# unsubscribe the default server
cherrypy.server.unsubscribe()
s1 = Server()
s2 = Server()
s1.socket_port = app_one_port
s2.socket_port = app_two_port
# subscribe the server to the `cherrypy.engine` bus events
s1.subscribe()
s2.subscribe()
def start_server():
bind_two_servers(8081, 8082)
cherrypy.engine.signals.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()
config = {
'/': {
'request.dispatch': dispatch.VirtualHost(**{
'localhost:8081': '/one',
'localhost:8082': '/two',
})
}
}
cherrypy.tree.mount(Root(), '/', config)
start_server()
This example will serve AppOne when coming from localhost:8081 and AppTwo when coming from localhost:8082.
The problem is that you can't do multiples cherrypy.tree.mount and expect to route into the different applications using the VirtualHost dispatcher, it assumes that the application resolution is done at that point and is only resolving the path of that application.
Having said all of that... I do not recommend this solution, it can get complicated and it would be better to have some other server in front (like nginx) and serve each path on different processes. This could be an alternative, only if you really really want to avoid any extra server or process in your setup.

Get the correct port number from LiveServerTestCase in Django 2.0

When trying to test the admin login using the following code, I found the self.live_server_url returns something like http://localhost:39346, where the port number is different on each running.
from django.test import LiveServerTestCase
from selenium import webdriver
class AdminLoginTests(LiveServerTestCase):
def setUp(self):
self.selenium = webdriver.Firefox()
super(AdminLoginTests, self).setUp()
def tearDown(self):
self.selenium.quit()
super(AdminLoginTests, self).tearDown()
def test_admin_login(self):
# ...
print('url: %s' %self.live_server_url)
How do I get the correct port number 8000 of the running server? Suppose I run the server through python manage.py runserver 0.0.0.0:8000. Thanks!
LiveServerTestCase spawns a new instance with that port on purpose. That way you can test a production environment without having to shutdown the production server (which by default runs on 8000).
However if you want to change the port that the debug is running on you can initialize to a different port number.
class TempTest(LiveServerTestCase):
def __init__(self):
super(TempTest, self).__init__()
self.port = 8910
def setUp(self)
# ....
This is what works for me under Django version 1.11.26
class TempTest(LiveServerTestCase):
port = 8888
host = "0.0.0.0" # If you want your test server to be public

python bottle integration tests

I have a rest api hosted using bottle web framework. I would like to run integration tests for my api. As part of the test, I would need to start a local instance of the bottle server. But run api in bottle framework blocks the execution thread. How do I create integration tests with a local instance of the server?
I want to start the server during setUp and stop it after running all my tests.
Is this possible with bottle web framework?
I was able to do it using multi threading. If there is a better solution, I will consider it.
def setUp(self):
from thread import start_new_thread
start_new_thread(start_bottle,(),{})
def my_test():
#Run the tests here which make the http call to the resources hosted using above bottle server instance
UPDATE
class TestBottleServer(object):
"""
Starts a local instance of bottle container to run the tests against.
"""
is_running = False
def __init__(self, app=None, host="localhost", port=3534, debug=False, reloader=False, server="tornado"):
self.app = app
self.host = host
self.port = port
self.debug = debug
self.reloader = reloader
self.server = server
def ensured_bottle_started(self):
if TestBottleServer.is_running is False:
start_new_thread(self.__start_bottle__, (), {})
#Sleep is required for forked thread to initialise the app
TestBottleServer.is_running = True
time.sleep(1)
def __start_bottle__(self):
run(
app=self.app,
host=self.host,
port=self.port,
debug=self.debug,
reloader=self.reloader,
server=self.server)
#staticmethod
def restart():
TestBottleServer.is_running = False
TestBottleServer.ensured_bottle_started()
TEST_BOTTLE_SERVER = TestBottleServer()

mod wsgi using apache and python

I have used mod_wsgi to create a web server that can be called locally. Now I just found out I need to change it so it runs through the Apache server. I'm hoping to do this without rewriting my whole script.
from wsgiref.simple_server import make_server
class FileUploadApp(object):
firstcult = ""
def __init__(self, root):
self.root = root
def __call__(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'POST':
post = cgi.FieldStorage(
fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=True
)
body = u"""
<html><body>
<head><title>title</title></head>
<h3>text</h3>
<form enctype="multipart/form-data" action="http://localhost:8088" method="post">
</body></html>
"""
return self.__bodyreturn(environ, start_response,body)
def __bodyreturn(self, environ, start_response,body):
start_response(
'200 OK',
[
('Content-type', 'text/html; charset=utf8'),
('Content-Length', str(len(body))),
]
)
return [body.encode('utf8')]
def main():
PORT = 8080
print "port:", PORT
ROOT = "/home/user/"
httpd = make_server('', PORT, FileUploadApp(ROOT))
print "Serving HTTP on port %s..."%(PORT)
httpd.serve_forever() # Respond to requests until process is killed
if __name__ == "__main__":
main()
I am hoping to find a way to make it possible to avoid making the server and making it possible to run multiple instances of my script.
The documentation at:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines
explains what mod_wsgi is expecting to be given.
If you also read:
http://blog.dscpl.com.au/2011/01/implementing-wsgi-application-objects.html
you will learn about the various ways that WSGI application entry points can be constructed.
From that you should identify that FileUploadApp fits one of the described ways of defining a WSGI application and thus you only need satisfy the requirement that mod_wsgi has of the WSGI application object being accessible as 'application'.

webapp2 DomainRoute is not matching

I'm trying to launch a webserver serving several sites under several subdomains.
I'm using Pythen with webapp2 and paste. My Server is behind a router that asigns a static IP adress to the server and forwards port 80. The router itself has no static IP adress assigned by my ISP so I'm using DDNS (lets say example.dlinkddns.com) .
In my folder hierarchy each folder represents a subdomain and is a python module.
Like this:
server/app.py
server/www
server/www/__init__.py
server/test
server/test/__init__.py
they should be reachable via www.mydomain.com and test.mydomain.com
I set *.mydomain.com to be a CNAME for example.dlinkddns.com
This is server/app.py:
import sys
import os
import webapp2
from webapp2_extras import routes
from paste import httpserver
DOMAIN = 'mydomain.com'
class Fallback(webapp2.RequestHandler):
def get(self, *args, **kw):
self.response.write('Fallback...\n'+str(args)+'\n'+str(kw))
def main():
dirs = [name for name in os.listdir(".") if os.path.isdir(name)]
dirs.remove('env') # folder created by package virtualenv - needed for paste
rs = []
for subdomain in dirs:
# import subdomain package
exec('import '+subdomain)
# add routes defined for subdomain
exec('rs += [routes.DomainRoute("'+subdomain+'.'+DOMAIN+'", '+subdomain+'.routes)]')
rs += [routes.DomainRoute("<domain:.*>",[webapp2.Route('/<:.*>',Fallback,name='fallback')])]
app = webapp2.WSGIApplication(rs)
httpserver.serve(app, host='0.0.0.0', port='80')
if __name__ == '__main__':
main()
And this is how my www package looks like:
__init__.py
import webapp2
class MainMain(webapp2.RequestHandler):
def get(self,target):
self.response.write('Hello, webapp2! www.mydomain.com at:'+target)
routes = [
webapp2.Route('/<target>', handler=MainMain, name='main-main')
]
The problem now is, when I visit www.mydomain.com the fallback handler seems to match but MainMain handler should.
The output is
Fallback... () {'domain':'0.0.0.0'}.
It looks like my app wouldn't recognize the domains at all. Same thing happens when I visit example.dlinkddns.com.
I also tried it without the fallback handler but then it only showed me the 404 page for every route and every domain...
I also tried to start the server with
httpserver.serve(app, host='192.168.178.33', port='80')
This is the static assigned IP address of my server in my LAN. The the output changes to
Fallback... () {'domain':'192.168.178.33'}.
What am I doing wrong? Thanks for any help!

Categories

Resources