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.
Related
import flask
import sentimentanalyzer
app: object = flask
#app.route("/")
def default() :
return "Hello world>>!!"``
#app.route("/predictsentiment/<query>",method=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == "__main__":
app.run()
You need to import Flask class from flask module.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
I see you have not found a solution yet.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
Though the above code is correct, your error may be the initialization or the structure of the app. Please post the structure.
init.py needs to be put in a directory and the directory is called.
Try renaming your init.py to app.py, should solve the error.
As a reference the Quickstart docs here: https://flask.palletsprojects.com/en/1.1.x/quickstart/
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
You need to create an object from the Flask class to get started.
And methods needs to be plural. (ref: https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods)
Not relevant tot the question the default route has invalid syntax with the double backticks resulting in:
File "/home/tom/tmp/test.py", line 8
return "Hello world>>!!"``
^
SyntaxError: invalid syntax
Regards,
Tom
You need to import the flask class from the flask module. Check how to make minimal application here
import flask
import sentimentanalyzer
app: flask.Flask = flask.Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>")
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if _name_== " main ":
app.run()
I would like to know, Is it possible to run a function after response from web.py service, which function takes long time to run?
Lets say some example as below.
file Name: code.py
import web
import time
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
try:
with open('filename.txt', 'a') as file:
for i in range(100):
time.sleep(1)
file.write("No of times: {}".format(i))
return "some json response"
except:
return "Exception occurred"
if __name__ == "__main__":
app.run()
When I run the above code, obviously it will take time because as we are using time module for sleep one sec and then write into file. So, I should wait 100 seconds for get the response from service.
I want to skip this 100 seconds waiting time.
Expected: First return response to client and then run this part in background?
Can somebody provide some solution. Thanks..
Have a look python documentation for Thread.run()
Note:
With background task you won't be able to return "Exception occurred" as you're doing now. I believe you're OK with it.
Here's a small easy solution. There are other ways too but I feel you should explore more by yourself since you're a python beginner. :)
import web
import time
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def writeToFile():
try:
with open('filename.txt', 'a') as file:
for i in range(100):
time.sleep(1)
file.write("No of times: {}".format(i))
# Log completion
except:
# Log error
def GET(self):
thread = Thread(target=writeToFile)
thread.start()
return {<myJSON>}
if __name__ == "__main__":
app.run()
I did the project in ex50. It works fine on ubuntu. However I can't get it run normally on win7. What's wrong with it? (My code is exactly the same as what it is in the book!)
app.py
import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
greeting = "Hello World"
return render.Index(greeting = greeting)
if __name__ == "__main__":
app.run()
Traceback on win7:traceback
And my project here on github~ https://github.com/ustcgcy/gothonweb
Don't use the trailing /on Windows. Instead of render = web.template.render('templates/') write render = web.template.render('templates').
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!
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.