Problems with CherryPy url-encoding - python

im trying to get german umlaute in my url variables.
This is my code:
class Root:
def echo(self,input):
return input
echo.exposed = True
if __name__ == '__main__':
cherrypy.quickstart(Root(),'/')
This works fine:
http://localhost:8080/echo/?input=äöüß
Result: äöüß
But when i try:
http://localhost:8080/echo/äöüß
I get: äöüÃ
Does anyone know the reason and how i can fix this?

Try this:
import cherrypy
class Root:
def echo(self,input):
return bytes(input, 'Latin-1')
echo.exposed = True
if __name__ == '__main__':
cherrypy.quickstart(Root(),'/')
or do this:
class Root:
#tools.encode(encoding='Latin-1')
def echo(self,input):
Cherrypy is by default encoded utf-8.
Hope this helps!

Related

Having trouble to understand how __str__ special method executes

I am not able to explain the behaviour of the following code when running it in PyCharm:
class Empty:
def __init__(self):
pass
def __str__(self):
print('in!')
return f'<{__name__}.Empty object at {hex(id(self))!r}>'
if __name__ == '__main__':
e = Empty()
The output:
in!
in!
There is no output when running the code from the terminal like this python .\my_script.py. May someone have an explanation for this? Thanks!

Python 3.5 code - classes not correct defined

I have a simple code problem and do not know what I do wrong. The import part is OK, when I get as an error message is that, I guess I make a mistake with the classes.
status_listener = SessionStatusListener()
TypeError: interface takes exactly one argument
So the code is:
import clr
clr.AddReference ("fxcore2")
from fxcore2 import O2GTransport, IO2GSessionStatus
class SessionStatusListener(IO2GSessionStatus):
def __init__(self):
IO2GSessionStatus.__init__(self)
self.connected = False
def onLoginFailed(self, error):
print ("*** LOGIN FAILED: %s" % error)
def onSessionStatusChanged(self, status):
print ("NEW STATUS: %s" % status)
if status == O2GSessionStatusCode.Connected:
self.connected = True
The main Application starts here
if __name__ == "__main__":
session = O2GTransport.createSession()
status_listener = SessionStatusListener()
Any advice is appreciated.
Pass an argument to SessionStatusListener, like it's telling you to. I would imagine that you need to change the __init__ body to something like
super().__init__(self)
instead of
IO2GSessionStatus.__init__(self)
I believe it is saying that
status_listener = SessionStatusListener()
Needs one argument, like this:
status_listener = SessionStatusListener(1)
I'm not sure exactly what types of data it's expecting, but you need to pass in an argument.

Custom route predicates in Pyramid

I am using some custom predicates in one of my Pyramid application. Since Pyramid version 1.5, when starting the app, the following message is displayed:
my_project\__init__.py:110: DeprecationWarning: The "custom_predicates"
argument to Configurator.add_route is deprecated as of Pyramid 1.5. Use
"config.add_route_predicate" and use the registered route predicate as a
predicate argument to add_route instead. See "Adding A Third Party
View,Route, or Subscriber Predicate" in the "Hooks" chapter
of the documentation for more information.
I would like to use the new method... but I cannot find one piece of advice in how to do that...
Even the doc illustrates the old method: https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#custom-route-predicates
I tried to defined my custom predicate in my my_project\__init__.py file, using something like:
def my_predicate(info, request):
if request.something:
return True
return False
def main(global_config, **settings):
...
config.add_route_predicate('my_predicate_name', my_predicate)
config.add_route('my_route_name','/route_name/', 'my_predicate_name')
...
But that does not have any effect, I know that using 'my_predicate_name' is not the good way... I know that I am missing something, but I just cannot get what...
EDIT
If I change my code to:
config.add_route('my_route_name','/route_name/', my_predicate_name=True)
Then Pyramid throws the following error:
NameError: global name 'my_predicate_name' is not defined
It looks like the add_route_predicate does not have any effect...
This location in the documentation should explain how to implementat a custom predicate: http://docs.pylonsproject.org/projects/pyramid/en/master/narr/hooks.html#view-and-route-predicates
Here is an additional example. The response in French should only be returned when lang=fr is in the query arguments otherwise the response in English matches by default.
So / returns Hello and /?lang=fr returns bonjour.
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello')
class LanguagePredicate():
def __init__(self, val, config):
self.val = val
def text(self):
return 'lang = %s' % (self.val,)
phash = text
def __call__(self, context, request):
return request.GET.get('lang') == self.val
def hello_world_fr(request):
return Response('bonjour')
def main():
config = Configurator()
config.add_route_predicate('lang', LanguagePredicate)
config.add_route('hello_fr', '/', lang='fr')
config.add_route('hello', '/')
config.add_view(hello_world_fr, route_name='hello_fr')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
return app
if __name__ == '__main__':
app = main()
server = make_server('0.0.0.0', 6547, app)
print ('Starting up server on http://localhost:6547')
server.serve_forever()

setUp section in unit-tests seems to be ignored

class MyTests(unittest.TestCase):
def SetUp(self):
""" Setting up expected default values """
self.test = RandomTest()
def testReturnsArrayWithTuples(self):
result = self.test.next() # Error
self.assert_(len(result), 5)
if __name__ == "__main__":
unittest.main()
I have a basic test, but it fails with this error message:
AttributeError: 'MyTests' object has no attribute 'test'
Eclipse intellisense is showing me self.test though. What am I missing please?
Ok, its quite embarrassing, as it was just a typo. :)
def SetUp(self): has to be lowercase def setUp(self): in order to be found and executed.
I hope it prevents someone else chasing ghosts like I did.

Tornado and Unicode

does tornado accept unicode in the adress?
#coding: utf-8 (there is # dont know how to show it here...)
import tornado.ioloop
import tornado.web
class Abdou(tornado.web.RequestHandler):
def get(self):
self.write("hi")
miaw = tornado.web.Application([
(u'/ééé', Abdou),
])
if __name__ == "__main__":
miaw.listen(8000)
tornado.ioloop.IOLoop
in Flask it worked !!!
from flask import Flask
miaw = Flask(__name__)
#miaw.route(u'/ééé')
def abdou():
return "hi!"
if __name__ == '__main__':
miaw.run()
NB: the same problem when using escape like /hello world , but in Flask it works!
NB2: thank you "wisty" for the edit :) now it appears more professional as a code :p
Look at tornado.escape.url_escape(value) and tornado.escape.url_unescape(value, encoding='utf-8').
Something like this:
#coding: utf-8 (there is # dont know how to show it here...)
import tornado.ioloop
import tornado.web
class Abdou(tornado.web.RequestHandler):
def get(self):
self.write("hi")
miaw = tornado.web.Application([
(tornado.escape.url_escape(u'/ééé'), Abdou),
])
if __name__ == "__main__":
miaw.listen(8000)
tornado.ioloop.IOLoop
You probably also want to be able to get urls that the user inputs. I think you do it like:
class Page(tornado.web.RequestHandler):
def get(self,title):
title = tornado.escape.url_unescape(title, encoding='utf-8')
self.write(title)
miaw = tornado.web.Application([
(tornado.escape.url_escape(u'/ééé/(*.)'), Page),
])
# you can get /ééé/page_name, where page_name can be unicode
if __name__ == "__main__":
miaw.listen(8000)
tornado.ioloop.IOLoop
it seems that it's a bug:
http://groups.google.com/group/python-tornado/browse_thread/thread/1f89cbeee05ba6fb/c028d3e4744eec8a?lnk=gst&q=unicode#c028d3e4744eec8a
and the link is dead :( the 404 is following me even here!

Categories

Resources