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!
Related
I am trying to mock test an endpoint that gets the time and date.
I have viewed several tutorials and python docs, but I am still getting stumped by the mock test.
Any help is appreciated greatly
from flask import Flask, redirect, url_for
import json
import urllib.request
import requests
app = Flask(__name__)
#app.route('/')
def welcome():
return "Hello"
#app.route('/<zone>')
def Endpoint(zone):
address = f"http://worldclockapi.com/api/json/{zone}/now"
response = urllib.request.urlopen(address)
result = json.loads(response.read())
time = result['currentDateTime']
return time
if __name__ == "__main__":
app.run(debug=True)
My attempt.
I think I am still calling the external element.
I want to use a fake JSON string and actually mock with that.
The first test passes when I run it. But I don't think it is a true mock.
#!/usr/bin/python
import unittest
from unittest import TestCase
from unittest.mock import patch, Mock
#name of endpoint program
import question
class TestingMock(TestCase):
#patch('question.Endpoint')
def test_call(self, MockTime):
current = MockTime()
current.posts.return_value = [
{"$id": "1", "currentDateTime": "2020-07-17T12:31-04:00", "utcOffset": "-04:00:00"}
]
response = current.posts()
self.assertIsNotNone(response)
self.assertIsInstance(response[0], dict)
#patch('question.Endpoint')
def test_response(mock_get):
mock_get.return_value.ok = True
respond = question.Endpoint()
assert_is_not_none(respond)
if __name__ == '__main__':
unittest.main()
You are conflicting with your root URL handler. Try changing #app.route('/<zone>') to #app.route('/time/<zone>'), then navigate to that url
The tornado testing subject doc is so simple, I am not quite sure how to do a unit test on tornado. like that:
here is a api.py:
import tornado
import logging
from tornado.web import RequestHandler
import time
class AnalyticsBWSpecificHour(RequestHandler):
def get(self):
return self.write({'message':'no get method'})
class Application(tornado.web.Application):
def __init__(self,**kwargs):
api_handlers = [
(r"/", AnalyticsBWSpecificHour),
]
logging.debug(api_handlers)
super(Application, self).__init__(api_handlers, **kwargs)
and the test_tornado.py :
from api import Application
from tornado.testing import AsyncHTTPTestCase
import tornado
import logging
logging.basicConfig(level=logging.DEBUG)
import unittest
class ApiTestCase(AsyncHTTPTestCase):
def get_app(self):
self.app = Application(debug=True)
return self.app
def test_status(self):
print(self.get_url('/'))
response = self.fetch(self.get_url('/'),method='GET')
self.assertEqual(response.code,200)
if __name__ == '__main__':
unittest.main()
even this is quite simple example, I also get the 599 error. please help me.
response = self.fetch(self.get_url('/'),method='GET')
self.fetch() calls self.get_url for you. Either do self.fetch('/') or self.http_client.fetch(self.get_url('/')), but don't mix the two.
Also don't pass debug=True in tests; the autoreload will do the wrong thing in a unittest environment.
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!
Hi i was writng simple web server...
here is code frament.
url = ('/comment','HandleComment','/question','HandleQuestion','/post','HandlePost')
class HandleAll:
.
.
webApi = web.application(urls, globals())
if __name__ == "__main__":
webApi.run()
rather than using 3 diffrent class(HandleComment, HandleQuestion, HandlePost), i want to check which URL called in if statment
can any body help me..?
thank you.
It defeats the purpose of using web.py a bit, but it is certainly possible to do it with one handler only:
import web
urls = ('/.*', 'Root')
class Root:
def GET(self):
url = web.url()
if url == '/comment': pass
elif url == '/question': pass
elif url == '/post': pass
def POST(self):
if web.url() == '/post':
pass
app = web.application(urls, globals())
if __name__ == "__main__":
app.run()
If the class-per-handler syntax is not to your liking, perhaps you should give Bottle a go.
I did everything according to the flask documentation, but I always get the error 404. I really don't get what I am doing wrong. Perhaps, someone can look at my code and give me a push in the direction of my mistake? It would be too generous, I am really stuck here for hours now and I am almost at the point to give up again. It is so frustrating.
my app:
import flask
app = flask.Flask(__name__)
def main():
register_blueprints()
app.run(debug=True)
def register_blueprints():
from pypi_org.views import home_views
from pypi_org.views import package_views
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
main()
my home_views.py file
import flask
import pypi_org.services.package_service as package_service
blueprint = flask.Blueprint('home', __name__, template_folder='templates')
#blueprint.route('/')
def index():
test_packages = package_service.get_latest_packages()
return flask.render_template('home/index.html', packages=test_packages)
#blueprint.route('/about')
def about():
return flask.render_template('home/about.html')
I found the answer to this in the 'final' github files provided for the course (see the link provided by OP), there's an addition of a couple lines in app.py:
if __name__ == '__main__':
main()
else:
register_blueprints()
Perhaps simplify app.py:
import flask
from pypi_org.views import home_views
from pypi_org.views import package_views
app = flask.Flask(__name__)
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
print (app.url_map)
app.run(debug=True)
Note the addition of the second last line prints all the URL routes to the terminal when you run the application, which helps for debugging.