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.
Related
I have a Python application in which for one specific API, I am trying to redirect it to another API present in another Flask application. To achieve this, I am using the below code:
`
#app.route('/hello')
def hello_name(name):
return redirect("http://localhost:8000/hello", 302)
`
Now, if I try to access my API by appending query parameters like http://localhost:6000/hello?name=Sidharth, it should be redirected to http://localhost:8000/hello?name=Sidharth. Can I get an advice on how this can be done?
I looked online and found that most of the posts are advising usage of url_for() but since I don't want to redirect to another view, I don't think url_for() will be beneficial in my case. With the code that I have written now, the query parameters are not being added to the redirected url.
Try to use HTTP status code 307 Internal Redirect instead of 302 like below:-
#app.route('/hello/')
def hello_name(name):
return redirect(url_for('http://localhost:8000/hello', args1=name), code=307)
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
I'm new to Flask and web development. I have a question about url parameters.
For example, I have an endpoint '/categories' which expect no url arguments. I experimented adding some random url parameter in curl like
curl localhost:5000/categories?page=1
It works like normal, I'm wondering if that is the expected behavior or should I handle this with some error or warning?
Also, if I expect an url parameter called 'id' and the request contains no url parameter or wrong url parameter. How should I handle this situation?
What status code should I abort in the above situations?
Thank you for any help.
You will need to inspect your query string (the values after ? in the URL) to see if the parameter exists and the value is valid. There are libraries to do this with a decorator, but you can do it manually as well. You will need to import the request object at the top of your module.
from flask import request
#app.route('/categories')
def categories():
id = request.args.get('id') # will return None if key does not exist
if id:
# id exists, validate value here
pass
else:
# no id, return error or something
pass
Related question:
How do you get a query string on Flask?
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'm experimenting with a Cloud Endpoint API in Python on App Engine, but I'm having some difficulty getting a simple request parameter.
I'm more familiar with Cloud Endpoints for Java, so I'm possibly (probably) missing something obvious. All I'm trying to do in this example is return the ServiceInfo object with an id specified in the url path, /services/<id>
I have a trivial response message class:
class ServiceInfo(messages.Message):
crs = messages.StringField(1)
services = messages.StringField(2)
and API class:
#endpoints.api(name='myApi', version='v1', description='My API', audiences=[endpoints.API_EXPLORER_CLIENT_ID])
class MyApi(remote.Service):
#No request body, but need to capture the id from the URL
ID_RESOURCE = endpoints.ResourceContainer(
message_types.VoidMessage,
id=messages.StringField(1, variant=messages.Variant.STRING, required=True))
#endpoints.method(ID_RESOURCE, ServiceInfo, path='services/{id}', http_method='GET', name='station.getServices')
def get_services(self, request):
print request.id
...
return ServiceInfo(crs=request.id, services=...)
Now, if I make a request through API explorer and enter ABC as the id field, I see this request:
GET /_ah/api/myApi/v1/services/ABC
But the response says
"Error parsing ProtoRPC request (Unable to parse request content: Message CombinedContainer is missing required field id)"
And when I print request.id, I get None.
All I'm trying to do is get the id from the path - am I missing something really obvious?
Thanks!
After re-visiting this after a couple of days, I restarted the local dev server (using gcloud preview app run ...) and it seems to now be working with the id in the url path (with no code changes) so perhaps the dev server environment had been caching an old version of one of my files?