how to shut down cherrypy server? - python

im on win7 ,i started a tutorial helloworld.py and everything doing fine but i don't know how to quit the service.i use
quit()
but command line give me an error message and exit.but service is still running and take my 8080 port. i hadn't find a way to shut down it manually.
File "C:\python32\lib\site-packages\cherrypy\process\wspbus.py", line 197, in
publish
output.append(listener(*args, **kwargs))
File "C:\python32\lib\site-packages\cherrypy\_cpserver.py", line 151, in start
ServerAdapter.start(self)
File "C:\python32\lib\site-packages\cherrypy\process\servers.py", line 167, in
start
wait_for_free_port(*self.bind_addr)
File "C:\python32\lib\site-packages\cherrypy\process\servers.py", line 410, in
wait_for_free_port
raise IOError("Port %r not free on %r" % (port, host))
IOError: Port 8080 not free on '0.0.0.0'

According to this page, quit() is not appropriate for this task.
Depending on how you run your server, you should consider using cherrypy.engine.exit:
>>> help(cherrypy.engine.exit)
exit(self) method of cherrypy.process.win32.Win32Bus instance
Stop all services and prepare to exit the process.

Include this in your python file.
#cherrypy.expose
def shutdown(self):
cherrypy.engine.exit()
Then add a link on your page.
<a id="shutdown"; href="./shutdown">Shutdown Server</a>

Related

OSError: [Errno 48] Address already in use In anki vector SDK (vectorCloud)

i'm really newbie in coding. i use macOS mojave. i try to use robot anki vector sdk and using rmountjoy92/VectorCloud code. at first i succeed opening the web flask based app. problem happens when i can't close my IDLE cause somehow i can't use control + C button to stop it. so i just use the close button in IDLE (one with red and x mark)
now when i try to reopen the code, its always showing error like this one:
Traceback (most recent call last):
File "/Users/Rasyid/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/Users/Rasyid/Library/Python/3.8/lib/python/site-packages/werkzeug/serving.py", line 1030, in run_simple
s.bind(server_address)
OSError: [Errno 48] Address already in use
i already read and try from this one OSError: [Errno 48] Address already in use
but it can't help because i'm total newbie.
the app.py code line 990 is like this one
#debug.setter
def debug(self, value):
self.config["DEBUG"] = value
self.jinja_env.auto_reload = self.templates_auto_reload
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
"""Runs the application on a local development server.
Do not use ``run()`` in a production setting. It is not intended to
meet security and performance requirements for a production server.
Instead, see :ref:`deployment` for WSGI server recommendations.
If the :attr:`debug` flag is set the server will automatically reload
for code changes and show a debugger in case an exception happened.
If you want to run the application in debug mode, but disable the
code execution on the interactive debugger, you can pass
``use_evalex=False`` as parameter. This will keep the debugger's
traceback screen active, but disable code execution.
It is not recommended to use this function for development with
automatic reloading as this is badly supported. Instead you should
be using the :command:`flask` command line script's ``run`` support.
.. admonition:: Keep in Mind
Flask will suppress any server error with a generic error page
unless it is in debug mode. As such to enable just the
interactive debugger without the code reloading, you have to
invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
Setting ``use_debugger`` to ``True`` without being in debug mode
won't catch any exceptions because there won't be any to
catch.
:param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
have the server available externally as well. Defaults to
``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
if present.
:param port: the port of the webserver. Defaults to ``5000`` or the
port defined in the ``SERVER_NAME`` config variable if present.
:param debug: if given, enable or disable debug mode. See
:attr:`debug`.
:param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
:param options: the options to be forwarded to the underlying Werkzeug
server. See :func:`werkzeug.serving.run_simple` for more
information.
.. versionchanged:: 1.0
If installed, python-dotenv will be used to load environment
variables from :file:`.env` and :file:`.flaskenv` files.
If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
environment variables will override :attr:`env` and
:attr:`debug`.
Threaded mode is enabled by default.
.. versionchanged:: 0.10
The default port is now picked from the ``SERVER_NAME``
variable.
"""
# Change this into a no-op if the server is invoked from the
# command line. Have a look at cli.py for more information.
if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
from .debughelpers import explain_ignored_app_run
explain_ignored_app_run()
return
if get_load_dotenv(load_dotenv):
cli.load_dotenv()
# if set, let env vars override previous values
if "FLASK_ENV" in os.environ:
self.env = get_env()
self.debug = get_debug_flag()
elif "FLASK_DEBUG" in os.environ:
self.debug = get_debug_flag()
# debug passed to method overrides all other sources
if debug is not None:
self.debug = bool(debug)
_host = "127.0.0.1"
_port = 5000
server_name = self.config.get("SERVER_NAME")
sn_host, sn_port = None, None
if server_name:
sn_host, _, sn_port = server_name.partition(":")
host = host or sn_host or _host
# pick the first value that's not None (0 is allowed)
port = int(next((p for p in (port, sn_port) if p is not None), _port))
options.setdefault("use_reloader", self.debug)
options.setdefault("use_debugger", self.debug)
options.setdefault("threaded", True)
cli.show_server_banner(self.env, self.debug, self.name, False)
from werkzeug.serving import run_simple
try:
run_simple(host, port, self, **options) **<< this one is line 990**
finally:
# reset the first request information if the development server
# reset normally. This makes it possible to restart the server
# without reloader and that stuff from an interactive shell.
self._got_first_request = False
and serving.py line 1030 is like this one
def inner():
try:
fd = int(os.environ["WERKZEUG_SERVER_FD"])
except (LookupError, ValueError):
fd = None
srv = make_server(
hostname,
port,
application,
threaded,
processes,
request_handler,
passthrough_errors,
ssl_context,
fd=fd,
)
if fd is None:
log_startup(srv.socket)
srv.serve_forever()
if use_reloader:
# If we're not running already in the subprocess that is the
# reloader we want to open up a socket early to make sure the
# port is actually available.
if not is_running_from_reloader():
if port == 0 and not can_open_by_fd:
raise ValueError(
"Cannot bind to a random port with enabled "
"reloader if the Python interpreter does "
"not support socket opening by fd."
)
# Create and destroy a socket so that any exceptions are
# raised before we spawn a separate Python interpreter and
# lose this ability.
address_family = select_address_family(hostname, port)
server_address = get_sockaddr(hostname, port, address_family)
s = socket.socket(address_family, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(server_address) **<<< this one is line 1030**
if hasattr(s, "set_inheritable"):
s.set_inheritable(True)
# If we can open the socket by file descriptor, then we can just
# reuse this one and our socket will survive the restarts.
if can_open_by_fd:
os.environ["WERKZEUG_SERVER_FD"] = str(s.fileno())
s.listen(LISTEN_QUEUE)
log_startup(s)
else:
s.close()
if address_family == af_unix:
_log("info", "Unlinking %s" % server_address)
os.unlink(server_address)
# Do not use relative imports, otherwise "python -m werkzeug.serving"
# breaks.
from ._reloader import run_with_reloader
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
else:
inner()
can someone kindly guide me with easy to understand word?
please tell me if i do mistake in my posting here, this is my first post.
thanks

Moving from localhost to real URL in Flask?

I'm developing a site with Python and Flask and want to move from localhost in my browser to my team's development server and development site but I'm having problems. I've already looked at the Flask documentation, which recommends using host='0.0.0.0' or specifying SERVER_NAME. Thusfar, neither of these things have helped. Here's a bit of code to show what I'm doing:
app = Flask(__name__)
if __name__ == '__main__':
app.secret_key = 'super secret key'
app.config['SERVER_NAME'] = 'https://example.org/blah'
app.run(host=app.config['SERVER_NAME'], port=4343, debug=True)
As you can see, instead of localhost:500, I want to be able to go into my browser and visit 'https://example.org/blah' and see the same things.
With this piece of code, I get this error:
(py34)user:~/flask$ python app.py
INFO - Connection with server established!
INFO - Server version meets recommendations (v2.9)
Traceback (most recent call last):
File "app.py", line 18, in <module>
app.run(host=app.config['SERVER_NAME'], port=4343, debug=True)
File "/home/me/anaconda3/envs/py34/lib/python3.4/site-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/home/me/anaconda3/envs/py34/lib/python3.4/site-packages/werkzeug/serving.py", line 674, in run_simple
s.bind((hostname, port))
socket.gaierror: [Errno -2] Name or service not known
If instead of using SERVER_NAME I use host='0.0.0.0', I don't get any errors and it will successfully start "Running on http://0.0.0.0:4343/" but I can't follow that url into my browser the same way I can when I connect to my localhost.
What do I need to do to get my flask app running on https://example.org/blah?
Also, if it helps to know, I have to ssh into my server.
If you run with host='0.0.0.0' from the server, you should be able to navigate to example.org:4343 and see your app.
Additionally, SERVER_NAME requires the port, per the documentation:
the name and port number of the server. Required for subdomain support (e.g.: 'myapp.dev:5000')
Finally, if you want to show you app without a port number, you either need to run it at port 80 (or 443) with root permissions, or using Nginx/Apache to route the request from your domain to the app.

How to very SIMPLY deploy a Twisted Server on OPenshift

I've got the right environment setup, python 2.7.5, Twisted installed and imports work in the Python Shell.
I have a very simple Server instance to display a landing page that Works on local machine fine.
from twisted.web import http
class MyRequestHandler(http.Request):
pages={
'/': '<h1>Geo-Address Server</h1>Twisted Server is Up and Running..',
'/test': '<h1>Test</h1>Test page',
}
def process(self):
print self.path
if self.pages.has_key(self.path):
self.write(self.pages[self.path])
else:
self.setResponseCode(http.NOT_FOUND)
self.write("<h1>Not Found</h1>Sorry, page does not exist")
self.finish()
class MyHttp(http.HTTPChannel):
requestFactory=MyRequestHandler
class MyHttpFactory(http.HTTPFactory):
protocol=MyHttp
if __name__=='__main__':
from twisted.internet import reactor
reactor.listenTCP(8080, MyHttpFactory())
reactor.run()
However, deploying this on the Openshift Server fails to run. If I try to run the script
python script.py &
I get:
reactor.listenTCP(8080, MyHttpFactory()) File
"/var/lib/openshift/5378ea844382ec89da000432/python/virtenv/lib/python2.7/site-packages/twisted/internet/posixbase.py",
line 495, in listenTCP
p.startListening() File "/var/lib/openshift/5378ea844382ec89da000432/python/virtenv/lib/python2.7/site-packages/twisted/internet/tcp.py",
line 979, in startListening
raise CannotListenError(self.interface, self.port, le) twisted.internet.error.CannotListenError: Couldn't listen on any:8080:
[Errno 13] Permission denied.
Reading through SO, most people just say to bind to port 8080(which I have done), but still I get the same error.
As the kb says
Please note: We don't allow arbitrary binding of ports on the
externally accessible IP address.
It is possible to bind to the internal IP with port range: 15000 -
35530. All other ports are reserved for specific processes to avoid conflicts. Since we're binding to the internal IP, you will need to
use port forwarding to access it:
https://openshift.redhat.com/community/blogs/getting-started-with-port-forwarding-on-openshift
Therefor, just find out the $OPENSHIFT_PYTHON_IP
echo $OPENSHIFT_PYTHON_IP
Then add that address to the reactor listener's interface
reactor.listenTCP(15000, MyHttpFactory(), interface='127.X.X.X')
Alternative(and the best) way to do it is by picking the value in the code. That way, if the IP changes dynamically, you still get the current IP
import os
local_hostname =os.getenv("OPENSHIFT_INTERNAL_IP")
..
..
reactor.listenTCP(15000, MyHttpFactory(), interface=local_hostname)
Note: You can only bind to the port range (15000-35530)

riak / python: unable to run a store() command

Attempting to follow the tutorial here.
After doing basic CRUD stuff, the tutorial has you edit the app.config file to use the LevelDB Backend for 2i, which in my case meant updating line 83 of /usr/local/Cellar/riak/1.4.2/etc/app.config from
{storage_backend, riak_kv_bitcask_backend},
to
{storage_backend, riak_kv_eleveldb_backend},
and then restarting riak.
I had thus far been running riak on port 8098, and their tutorial here references port 10017 instead:
# Starting Client
client = riak.RiakClient(pb_port=10017, protocol='pbc')
# Creating Buckets
customer_bucket = client.bucket('Customers')
order_bucket = client.bucket('Orders')
order_summary_bucket = client.bucket('OrderSummaries')
# Storing Data
cr = customer_bucket.new(str(customer['customer_id']),
data=customer)
cr.store()
if I try to run the code as written, I get this:
File "r.py", line 104, in <module>
cr.store()
File ".../riak/riak-python-client-master/riak/riak_object.py", line 281, in store
timeout=timeout)
File ".../riak/client/transport.py", line 127, in wrapper
return self._with_retries(pool, thunk)
File ".../riak/client/transport.py", line 82, in _with_retries
raise e.args[0]
socket.error: [Errno 61] Connection refused
suggesting that, clearly, the Riak client is not running on port 10017.
However, when I change it to port 8098
client = riak.RiakClient(pb_port=8098, protocol='pbc')
the application just freezes on the cr.store() line. Is there some thing where the eleveldb backend is expecting to run on a port other than default?
never mind, 8098 is the http port, when I changed it to port 8087, the default port, it works fine

"getaddrinfo() argument 1 must be string or None" error starting dev_appserver.py on Linux

I'm getting re-started with App Engine after not having used it in a while. I'm using the 64-bit Linux Go runtime, version 1.8.1.
I believe I'm following the steps from the documentation correctly, and I believe I'm doing what's worked correctly in the past, but I'm getting this error when attempting to launch dev_appserver.py:
$ dev_appserver.py .
INFO 2013-07-11 07:24:45,919 sdk_update_checker.py:244] Checking for updates to the SDK.
INFO 2013-07-11 07:24:46,230 sdk_update_checker.py:288] This SDK release is newer than the advertised release.
WARNING 2013-07-11 07:24:46,443 simple_search_stub.py:955] Could not read search indexes from /tmp/appengine.batterybotinfo.darshan/search_indexes
Traceback (most recent call last):
File "/home/darshan/bin/dev_appserver.py", line 182, in
_run_file(__file__, globals())
File "/home/darshan/bin/dev_appserver.py", line 178, in _run_file
execfile(script_path, globals_)
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 695, in
main()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 688, in main
dev_server.start(options)
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 659, in start
apis.start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/api_server.py", line 137, in start
super(APIServer, self).start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 295, in start
if self._start_all_dynamic_port(host_ports):
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 348, in _start_all_dynamic_port
server.start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 194, in start
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
TypeError: getaddrinfo() argument 1 must be string or None
My first thought was that I might be using an incorrect version of Python. Sure enough, I'm using 2.7.5, and the documentation clearly states that 2.5 is necessary. However, the documentation seems to be outdated, because after installing 2.5 and setting my system to use it, I got this error:
Error: Python 2.5 is not supported. Please use version 2.7.
Okay, so back to 2.7.5 and my initial error.
I'm not sure if this is a bug in the dev_appserver.py Python code (I'm guessing not, as it's been out for a month), an issue with my Python installation, or something else about my system that isn't configured according to Google's expectations.
I'd rather not mess with the dev_appserver.py code unless necessary, but I'm happy to poke at it to help figure out what's going wrong. The error is on line 194; here are lines 190-195:
# AF_INET or AF_INET6 socket
# Get the correct address family for our host (allows IPv6 addresses)
host, port = self.bind_addr
try:
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
I've determined that the containing method is called twice. The first time host is always "127.0.0.1" and port is 0. The second time is the one that crashes; host is always 10 (an int, not a string), and port is a seemingly-random five-digit int.
I've tried hard-coding host to "127.0.0.1" and port to either 8080 or 0, but then I get another error. I feel in over my head, and I suspect I'm not going to resolve the real issue by changing things I don't really understand. Googling for the error message hasn't helped.
Persistent Googling eventually paid off. Despite this question having a very different (and much more informative) error message, the solution turned out to be the same: ensure that /etc/hosts contains only a single entry for localhost.
Notably, my system contained both of these lines:
127.0.0.1 localhost
::1 localhost
Commenting out the second (and adding a comment to document why) solved my issue:
127.0.0.1 localhost
# Having multiple localhost entries causes App Enginge dev_appserver.py to fail.
# IPv6 not currently needed, and the dev server IS needed, so commenting out.
#::1 localhost
dev_appserver.py now starts and works properly.
If you edit lines 189-194 to this, it should work until Google releases an update. This is basically just checking the type of host and returning early if it isn't a string.
189 # AF_INET or AF_INET6 socket
190 # Get the correct address family for our host (allows IPv6 addresses)
191 host, port = self.bind_addr
192 try:
193 if type(host) is not str:
194 return
195 info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
196 socket.SOCK_STREAM, 0, socket.AI_PASSIVE)

Categories