I have been uploading a new version of my app engine application and after uploading when I make a request I get this as a response:
__init__() takes exactly 1 argument (3 given)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1076, in __call__
handler = self.handler(request, response)
TypeError: __init__() takes exactly 1 argument (3 given)
I have no idea what to do at all, I've commented parts of my code, uncommented them, I've uploaded the code to different GAE apps I have, even multiple versions of those apps.
I dont even know where to start can anyone please tell me what this error could even mean? I will provide any information you request, thank you in advance.
EDIT:
This is what the handler that i have added looks like:
class GCMRegister(webapp2.RequestHandler):
def post(self):
regid = self.request.get("regId")
if not regid:
self.response.out.write('Must specify regid')
else:
u = usuario()
u.name = "deadlybacon" # ax_length = 140)
u.mail = "testmail#hotmail.com" # (max_length = 256, db_index = True
u.password = "password" #max_length = 140)
u.put()
u.push_key(regid)
My WSGIApplication looks like this:
application = webapp2.WSGIApplication([
('/', MainPage),
('/indexData', indexData),
('/ajaxLogIn', ajaxLogIn),
('/createGroup', createGroup),
('/masterServices', masterServices),
('/groupInfo', groupInfo),
('/groupInviteTo', groupInviteTo),
('/acceptNotif', acceptNotif),
('/adventureCreate', createAdventure),
('/adventureAppointTo', adventureAppointTo),
('/addNewPrueba', addNewPrueba),
('/listPoolPruebas', listPoolPruebas),
('/addExistingPrueba', addExistingPrueba),
('/gcm/register', GCMRegister),
]) #, debug=True, config = config)
at first I assumed it was the debug and config, that is why i commented it, it makes no difference, the same error happens no matter what
Try this:
class HomeHandler(webapp2.RequestHandler):
def __init__(self, request, response):
self.initialize(request, response)
...
Related
Trying to get the GET parameters from the URL. I have it working in my __init__.py file, but in a different file its not working.
I tried to use with app.app_context(): but I am still getting the same issue.
def log_entry(entity, type, entity_id, data, error):
with app.app_context():
zip_id = request.args.get('id')
RuntimeError: working outside of request context
Any suggestions?
Additional Info:
This is using Flask web framework which is setup as a service (API).
Example URL the user would hit http://website.com/api/endpoint?id=1
As mentioned above using `zip_id = request.args.get('id') works fine in the main file but I am in runners.py (just another file with definitions in)
Full traceback:
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
File "/Users/ereeve/.virtualenvs/pi-automation-api/lib/python2.7/site-packages/werkzeug/wsgi.py", line 703, in __next__
return self._next()
File "/Users/ereeve/.virtualenvs/pi-automation-api/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
for item in iterable:
File "/Users/ereeve/Documents/TechSol/pi-automation-api/automation_api/runners.py", line 341, in create_agencies
log_entry("test", "created", 1, "{'data':'hey'}", "")
File "/Users/ereeve/Documents/TechSol/pi-automation-api/automation_api/runners.py", line 315, in log_entry
zip_id = request.args.get('id')
File "/Users/ereeve/.virtualenvs/pi-automation-api/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/ereeve/.virtualenvs/pi-automation-api/lib/python2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object
return self.__local()
File "/Users/ereeve/.virtualenvs/pi-automation-api/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
Def in the same file calling the log_entry def
def create_agencies(country_code, DB, session):
document = DB.find_one({'rb_account_id': RB_COUNTRIES_new[country_code]['rb_account_id']})
t2 = new_t2(session)
log_entry("test", "created", 1, "{'data':'hey'}", "")
I am making a small project and I have a main file, called blog.py and a separate file called users.py in a folder called source.
The layout of the project so far is:
MainFolder
|_blog.py
|
|_source
|_user.py
So, my user.py is very simple and it has a #staticmethod:
from google.appengine.ext import db
class User(db.Model):
username = db.StringProperty(required = True)
pwd_hash = db.StringProperty(required = True)
email = db.StringProperty()
#staticmethod
def searchByUsername(anUserName):
usersList = db.GqlQuery("select * from User where username='" + anUserName + "'")
user = None
for theUser in usersList:
user = theUser
return user
In my blog.py file I try to call that method by making User.searchByUsername(anUserName), however when I do so everythning blows up and I end up with an error (check last 2 lines):
Traceback (most recent call last):
File "/home/pedro/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1519, in __call__
response = self._internal_error(e)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/pedro/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/home/pedro/google_appengine/hw5/blog.py", line 202, in post
user = User.searchByUsername(username)
NameError: global name 'User' is not defined
I am using from source import user in my blog.py file, and the sources folder also has the __init__.py blank folder, so I know that file is being correctly imported.
Further more, if I just copy/paste the contents of the user.py file into the blog.py file everything works fine (but the I the code gets big and not organized). how can I fix this?
By doing from source import user, you are importing the module user, not the class User inside it. If you want to import that class, you should do from source.user import User. Or you can do from source import user and then refer to the class as user.User.
The staticmethod has nothing to do with it. As the error message suggests, the issue is that it does not know what User is, so it can't even begin to call a method of that class.
Sounds like you may have forgotten to import User into blog.py:
from source.user import User
I have the following very simple app:
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
When I run this, I get the following Exception:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/me/dev/project/src/main.py", line 22, in do_in_request
app(*args, **kwargs)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 249, in error_router
if self._has_fr_route():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 230, in _has_fr_route
if self._should_use_fr_error_handler():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 211, in _should_use_fr_error_handler
adapter = self.app.create_url_adapter(request)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1601, in create_url_adapter
return self.url_map.bind_to_environ(request.environ,
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/me/dev/project/src/lib/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
So I tried to put my entire app into what I thought would be the request context. In the code above, both the Flask object and the Api object are being instantiated once, and can be called by the server multiple times. From the traceback, it looks like the instantiation should happen within a request context, so I wrapped it like this:
def do_in_request(*args, **kwargs):
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
app(*args, **kwargs)
app = do_in_request
That still raises the same error. What's going on, what do they mean by 'request context', and how do I fix this?
I started from scratch using the App Engine Flask Skeleton and added flask-restful as a dependency in requirements.txt and then just added more or less the code you have above and it worked without an issue. I added the repository to my github here if you want to use it - you can see the changes I made to the skeleton in this commit.
I'm not sure why your example isn't working, but one thing I noticed that could be causing issues is that you're doing from lib.flask .... It seems your third-party packages live in lib and you haven't necessarily "lifted" lib into your sys.path. The skeleton includes a vendoring library that makes sure that this is handled properly. It might be a potential source of the problem.
Either way, I hope the forked skeleton can help you get up and running.
I have a problem here.
I have been using $resource to do simple GET, but recently i have a large amount of data to send to the server, but gives a 414 Error URI too large. I know that one of the solution is to use POST instead of GET.
I tried to search for solutions such as $http.post and passing parameters to $http, but to no avail. Can someone give me a tutorial on how should i do it?
Edit:
Here is what i have done:
var data_2 = $.param({'method':"update_proj",
'proj_id': proj_id,
'ptitle': project.title,
'pdescription': p_desc,
'pexposure': tech,
'pcompany': project.company,
'pteamsize':project.teamsize,
'ppoc': project.poc,
'pemail': c_email,
'pcontact': project.contact,
'pimg':project.img,
'pvideo':project.video,
'prskill': rskills,
'poutcome': project.outcome});
$http({method:'update_proj',
url: "http://osmosisgal.appspot.com/update_proj",
data: data_2,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data,status){
...
});
Here is my python code on GAE:
class ActionHandler(webapp.RequestHandler):
def update_project(self):
proj_id = self.request.POST["proj_id"]
.
.
.
But i still have this error
Traceback (most recent call last):
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~osmosisgal/1.366101252356646323/new_backend.py", line 1274, in update_project
proj_id = self.request.POST["proj_id"]
File "/python27_runtime/python27_lib/versions/third_party/webob-1.1.1/webob/multidict.py", line 312, in __getitem__
return self._decode_value(self.multi.__getitem__(self._encode_key(key)))
File "/python27_runtime/python27_lib/versions/third_party/webob-1.1.1/webob/multidict.py", line 568, in __getitem__
raise KeyError("No key %r: %s" % (key, self.reason))
KeyError: "No key 'proj_id': Not a form request"
From documentation you can see that method is getting the type of method and not the url, in first place.
$http({method: 'POST', url: '/someUrl', data: my_data}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
For you data you can create a json object with pairs, key-value and pass it to the function like above.
Also do not forget to pass $http in your controller definition.
function MyController($scope, $http) {...};
I managed to solve it. Initially I did not host all my static files in GAE, after i hosted it, everything works.
I am using Nick Johnsons Webapp & Templates application as a base for what I am trying to do. I am getting a "AttributeError: 'NoneType' object has no attribute 'write'" when I try to call the render_template. I know it is because when I instantiate the object "Capture" as X, it doesn't have a response property. I have looked everywhere to find a solution but I cannot find one anywhere.
NOTE: There are other ways to do this, but I need it to work as closely to how I have it setup!
Traceback:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/Users/userx/Documents/_FRESHCUTZ MEDIA/Google/GAE - Test web form 1 /testwebform1/main.py", line 41, in post
x.calculateYear(name, age)
File "/Users/userx/Documents/_FRESHCUTZ MEDIA/Google/GAE - Test web form 1 /testwebform1/main.py", line 49, in calculateYear
self.response.write(self.render_template('index.html', **template_args))
AttributeError: 'NoneType' object has no attribute 'write'
MAIN.PY
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_template(filename, **template_args))
class MainPage(BaseHandler):
def get(self):
template_args = {}
self.render_template('index.html', **template_args)
class CaptureDetails(BaseHandler):
def post(self):
name = self.request.get("name").strip()
age = self.request.get("age").strip()
x = Calculate()
x.calculateYear(name, age)
class Calculate(BaseHandler):
def calculateYear(self, name, age):
template_args = {"age": age}
self.render_template('name.html', **template_args)
app = webapp2.WSGIApplication([
('/', MainPage),
('/capture', CaptureDetails),
('/age', Calculate)
], debug=True)
What am I doing wrong? Any help/suggestions are greatly appreciated!
Does it fit your criteria if you make calculateYear a function of your BaseHandler class (or elsewhere if more applicable)? As you guessed, your x isn't being treated as a proper response. When you invoke a webapp2.RequestHandler handler, it calls the method associated with the type of request (so in your case, since you are posting a form, it will call post(), as you know). When you instantiate x and call calculateYear, you aren't specifying a particular method (def get(self), def post(self), etc.), so there is no preparation of a response (when I have a chance I'll dig a little to confirm that this is actually the case - I could be mistaken :) ).
Can't test this right now, but assuming you need to call calculateYear from more than just the CaptureDetails handler, would this work? Here you would be referencing self in the context of your post method, which would invoke the response handling:
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_template(filename, **template_args))
def calculateYear(self, name, age):
template_args = {"age": age}
self.render_template('name.html', **template_args)
Which you could then call from your CaptureDetails handler like:
class CaptureDetails(BaseHandler):
def post(self):
name = self.request.get("name").strip()
age = self.request.get("age").strip()
# Call the function and write the response
self.calculateYear(name, age)
By instantiating Calculate yourself in your CaptureDetails.post method you're not creating it in the same way that WSGIApplication does, so the properties aren't available. Specifically, you're not passing a response to it, so not surprisingly trying to reference it doesn't work.
In this case, I'd copy the contents of calculateYear into your post method - you're not really saving anything by having to create the instance and then call the method on it.
If calculateYear gets more complicated, and you don't want the duplication, then I'd introduce a new method that could be called by both of your hander methods. (It's not really clear from this example though why the Calculate class exists - it doesn't have a 'get' method, so mapping it to /age as you have done isn't going to work.)
Try using self.response.out.write instead of self.response.write.