I'm trying to retrieve the URL of my app in GAE + python + flask and get the following error when I run it locally:
NameError: name 'self' is not defined
Here's the snippet of code I'm utilizing to retrieve the URL path and display it.
import Flask, session, etc etc
...
#app.route('/')
def main():
if 'username' in session:
message = self.request.path
return render_template('main.html', username=session['username'], message=message)
return redirect(url_for('login'))
When I run the app locally on my Ubuntu machine I get the NameError copied above. I've searched in StackOverflow and some posts mention that 'self' should be invoked inside a method to exist. I'm invoking 'self' inside def main (), so I expect it to work but doesn't. It looks like I'm missing something about the scope of 'self'.
Any ideas what's wrong? Once this works I'll upload it to GAE in the cloud.
Thanks!
There is no self in the function. Use:
message = request.path
Related
I am trying to run the following code but I am getting a {"detail":"Method Not Allowed"} error when I open http://localhost:8000/predict.
The code:
from fastapi import FastAPI
app = FastAPI()
#app.post("/predict")
def predict_(request: str):
return {"message": 'Hellooo!'}
What's the problem with my code?
I searched online for similar examples but I got the same error! For example this one: https://codehandbook.org/post-data-fastapi/
It's because when you open the page in a browser, it makes a GET request, but your app only handles POST. Change to #app.get(...), and you should be able to see it in a browser. Or, navigate to http://localhost/docs and use the interactive documentation to test it as it is.
I am creating a REST API using python flask. The API is ready and works on port number 8000 of my localhost. Now I intend to give this REST API a user friendly interface for which I decided to go with python - restplus. I thought of calling this service (running on 8000) internally from swagger application running on 5000
I was able to create the basic structure of the API (Swagger). The code for which looks like this:
import flask
from flask import Flask, request
from flask_restplus import Resource, Api
app = Flask(__name__)
api = Api(app)
#api.route('/HybridComparator/<string:url2>/<string:url1>')
class HybridComparator(Resource):
def get(self, url1, url2):
print(url1)
print(url2)
return url1 + ' ' + url2
if __name__ == '__main__':
app.run(debug=True)
The application as a whole runs seamlessly (with random strings as parameters) on port 5000. But when the URLs I pass are actual links, the application returns a response of 404 - Not found. Further to my investigation I realized the culprit being '/' embedded within the links I try to provide. Is there a way to handle URLs in particular?
Should I encode them before sending a request. (This will make my parameters look ugly). Is there something I am missing?
This is an entirely old question and I am sure you solved your problem by now.
But for new searchers, this may come in handy;
replace <string:url2>/<string:url1> with <path:url2>/<path:url1>
it seems that :
#api.route('/HybridComparator/<path:url2>/<path:url1>')
should fix it ,it fixes the 404 but i am getting only "http:/" part of the param
I am facing a problem with flask url routing; it seems routes are not working as expected.
Under project/src/views.py, I have the following sample routes
from flask import (Flask,request,jsonify,Blueprint)
my_view = Blueprint('my_view', __name__)
#my_view.route('/',methods=("GET",))
#my_view.route('/index',methods=("GET",))
def index():
....
<return response code here>
#my_view.route("/key/<inp1>/<inp2>", methods=("POST","GET"))
def getKey(inp1=None, inp2=None):
....
<return response code here>
Now, under project/src/app.py, I have the following code
from ../src.views import my_view
my_app = Flask("myappname")
my_app.register_blueprint(my_view)
my_app.run(debug=True,host=APP_IP,port=APP_PORT)
Now, when I access the URL http://ip:port/index or http://ip:port/key... with valid parameters, it returns 404, with the message "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I believe mentioned routes are not working.
The first issue spotted is with your methods parameter. It expects a list/tuple but you're passing a string ('GET'). Change to methods=('GET', ). Note the comma after 'GET' here. Or to avoid potential confusion in the future, use methods=['GET']
The second issue is the way you're import my_view in app.py. Since views.py and app.py are in the same directory, and you're starting your flask app inside that directory, you can just do:
from views import my_view
However you should look into structuring your app as a Python Package
The third issue is a missing from flask import Flask. Maybe you overlooked this when you posted your code.
I tested your code with the above fixes and it works like it should.
EDIT: Thanks to #dirn for pointing out that tuples are accepted for methods parameter.
I know this is a duplicate question but by referring previous answers i couldn't find the solution yet.
I am using Google report api to fetch logs.
Please refer this link: https://developers.google.com/admin-sdk/reports/v1/libraries
Everything goes well and I am able to generate authorize URL using scope,client id etc.
But I am not able to redirect user to URL to fetch "code" from authorize URL.
I tried using webapp2 script but throws error = AssertionError: Request global variable is not set.
Here is the code I am using for redirection:
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
import ipdb;ipdb.set_trace()
path='my authorize url path'
return self.redirect(path) #throws error on this line
a1=MainPage() #object to call class
a2=a1.get() #call method of class
Where i am going wrong ? If webapp2 having standard bug for self.redirect, then which other framework can help to to perform same operation?
If i use app = webapp2.WSGIApplication([('/', MainPage)]) instead of creating objects then it doesnt even call get(self) function.
Any help would be appreciated.
Thanks.
I have a web.py app I'm running through mod_wsgi locally (http://localhost/...). I've gotten to the point of adding authentication to my app and wanted to use web.py's builtin module. I started with a brief example found here: http://log.liminastudio.com/programming/howto-use-openid-with-web-py
import web, web.webopenid
urls = (
r'/openid', 'web.webopenid.host',
r'/', 'Index'
)
app = web.application(urls, globals())
class Index:
def GET(self):
body = '''
<html><head><title>Web.py OpenID Test</title></head>
<body>
%s
</body>
</html>
''' % (web.webopenid.form('/openid'))
return body
if __name__ == "__main__": app.run()
This works well enough running in the terminal and going to http://localhost:8080/. Another example http://c-farrell.blogspot.com/2010/11/usrbinenv-pythonimport-webfrom-web.html does a similar technique but makes more sense to me.
#!/usr/bin/env python
import web
from web import webopenid
urls = (
'/', 'index',
'/openid', 'webopenid.host',
)
... more code ...
class index:
def GET(self):
oid = webopenid.status()
if not oid:
return 'please log in: ' + \
webopenid.form('/openid')
else:
return 'you are logged in as:' + \
webopenid.form('/openid')
Here's where I get a little lost. From what I can tell, the argument passed to form is the return URL after signing in. For example, if I put 'http://www.yahoo.com/' it will take me there after every login attempt. I feel like this should point back to my own controller and just check there, but the convention seems to be to use the web.webopenid.host controller, which I guess handles the id and returns to the base '/' url. I think I'm getting there, but the status returned is always None.
From what I gather then, this is either a code issue, or there's something in my apache configuration that is keeping the authentication from working. In web.webopenid, the library creates a .openid_secret_key file in the same directory as the web server. When I run the example code, this gets created. When I run my code through apache, it does not (at least not in the cgi-bin. Somewhere else?) Anyway, if this file isn't being generated or being regenerated every time, it will keep me from logging in. I believe it's an apache issue as I tried running my app through the web.py webserver and I did get the file created and I can authenticate. All I can conclude is this file isn't being written and every subsequent query tries a new file and I can never authentication. Can any apache/mod_wsgi gurus explain to me where this file is being written or if this is the actual problem?
Most likely obvious causes for this were given in answer to same question on mod_wsgi list. See:
https://groups.google.com/d/msg/modwsgi/iL65jNeY5jA/KgEq33E8548J
It is probably a combination of the first two, current working directory and Apache user access rights.