I have the code like below:
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except Exception, error_message:
logging.exception('Failed, exception happened - %s' % error_message)
but sometimes it fails with DeadlineExceededError? Should not this DeadlineExceededError be caught by my code?
The exception details:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/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~myapp/1.375970700643773844/myapp.py", line 424, in get
url, response = call_api(origin=origin, destination=destination, date=date_.strftime('%Y-%m-%d'))
File "/base/data/home/apps/s~myapp/1.375970700643773844/myapp.py", line 288, in call_api
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 270, in fetch
return rpc.get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 612, in get_result
return self.__get_result_hook(self)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 375, in _get_fetch_result
rpc.check_success()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 585, in check_success
self.__rpc, err)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 196, in Call
for key, function, srv, num_args in self.__content:
DeadlineExceededError
To answer your specific question, "Should not this DeadlineExceededError be caught by my code?":
The DeadlineExceededError class extends BaseException instead of Exception, so your except clause will never be called.
from google.appengine.runtime import DeadlineExceededError
my_error = DeadlineExceededError()
isinstance(my_error, Exception) # False
isinstance(my_error, BaseException) # True
First approach
Try excepting the DeadlineExceededError class by importing
from google.appengine.runtime import DeadlineExceededError and doing it like this:
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except DeadlineExceededError, error_message:
logging.exception('Failed, exception happened - %s' % error_message)
Read more about it on the documentation.
Second Approach
I've faced this error before, and an approach I've followed was not to set which exception class I was trying to catch. I just called except.
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except:
logging.exception('First failure')
# try again your request as suggested by the documentation
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except:
logging.exception('Second failure')
return None
But I wasn't able to catch the error message, and instead of just logging an error message, I tried the request once again when the exception was raised, as the link I posted above suggests.
Some good links you should read
You should read this about Dealing with DeadlineExceedError.
There is also Backends, which allow you to avoid this request timer; with backends, there is no time limit for generating and returning a request.
Hope this helps you.
Related
I've tried the following command:
#client.command
#commands.has_permissions(ban_members=True)
async def unban(ctx, *, member : discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_disc = member.split("#")
for banned_entry in banned_users:
user = banned_entry.user
if(user.name, user.discriminator)==(member_name, member_disc):
await ctx.guild.unban(user)
unbanned = discord.Embed(title="Unban <:ban:756532045299318784>", description=f"**{member}** is unbanned! <a:tick:756202944461930567>", color=discord.Color.green(), timestamp=datetime.datetime.utcnow())
await ctx.send(embed = unbanned)
await ctx.send(f"Couldn't find **{member}** named person. iTs CaSe SeNsItIvE!")
Which is just a simple code to enter a name like "Wumpus#0001".
But it shows me up a big error:
Traceback (most recent call last):
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/Fujitsu/Desktop/Yupiter/bot.py", line 40, in on_command_error
raise error
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/Fujitsu/Desktop/Yupiter/bot.py", line 40, in on_command_error
raise error
discord.ext.commands.errors.CommandNotFound: Command "unban" is not found
"Command "unban" is not found".
What can I do, and is there a way to allow entering an ID instead of a username#discriminator?
You just made a simple mistake. #client.command must be #client.command().
i just deployed the appengine application and when i do a rest get call to trigger the queue i am getting below UnknownQueueError. It appears that the exception is thrown at the the below source code line. Any ideas on what is causing the issue. I tested locally and it works perfectly fine.
q.add(task)
Exception
Exception on /tasks/stock/prices/dispatch [GET]
Traceback (most recent call last):
File "/base/data/home/apps/s~xxxxx-173913/internal-
api:20170716t091842.402709903291335684/lib/flask/app.py", line 1817,
in wsgi_app
response = self.full_dispatch_request()
File "/base/data/home/apps/s~xxxxx-173913/internal-
api:20170716t091842.402709903291335684/lib/flask/app.py", line 1477,
in full_dispatch_request
rv = self.handle_user_exception(e)
File "/base/data/home/apps/s~xxxx-173913/internal-
api:20170716t091842.402709903291335684/lib/flask/app.py", line 1381,
in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/base/data/home/apps/s~xxxxxx-173913/internal-
api:20170716t091842.402709903291335684/lib/flask/app.py", line 1475,
in full_dispatch_request
rv = self.dispatch_request()
File "/base/data/home/apps/s~xxxxxx-173913/internal-
api:20170716t091842.402709903291335684/lib/flask/app.py", line 1461,
in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~xxxx-173913/internal-apixxx/
internal/tasks/stock_prices_dispa
tch.py", line 34, in run
q.add(task)
File"/base/data/home/runtimes/python27/python27_lib
/versions/1/google/appengine/api/taskqueue/taskqueue.py",
line 2128, in add
return self.add_async(task, transactional).get_result()
File"/base/data/home/runtimes/python27/python27_lib
/versions/1/google/appeng
ine/api/apiproxy_stub_map.py", line 613, in get_result
return self.__get_result_hook(self)
File "/base/data/home/runtimes/python27/
python27_lib/versions/1/google/appeng
ine/api/taskqueue/taskqueue.py", line 2162, in ResultHook
raise exception
UnknownQueueError
Source Code
task = Blueprint('tasks.stock.prices.dispatch', __name__)
#task.route('/tasks/stock/prices/dispatch')
def run():
q = taskqueue.Queue('push-queue')
from_date = request.args.get('from')
to_date = request.args.get('to')
with open(os.path.join(os.path.dirname(__file__),
"../resources/dow_30.csv")) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
ticker = row['TICKER']
stock_code = row['StockCode']
task = taskqueue.Task(
url='/tasks/stock/prices/shard',
target='internal-api',
headers={'Content-Type' : 'application/json'},
payload=json.dumps({'ticker': ticker, 'stock_code': stock_code, 'from' : from_date, 'to' : to_date}))
logging.info("StockCode :=" + stock_code)
q.add(task)
return "OK"
When i deployed the application i forgot to deploy queue.yaml. Once i did the below ( provided by #DanCornilescu) it resolved the issue.
gcould app deploy <path_to_your_queue.yaml>
I am try to fetch some tweets in Google App Engine and doing some analysis on that tweets.
Due to some issue in urllib3, I am facing the following error :
AttributeError: 'NoneType' object has no attribute 'wrap_socket'
The last three call are :
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connectionpool.py", line 304, in _make_request
self._validate_conn(conn)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connectionpool.py", line 722, in _validate_conn
conn.connect()
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connection.py", line 164, in connect
self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)
AttributeError: 'NoneType' object has no attribute 'wrap_socket'
Traceback (most recent call last):
INFO 2014-08-24 10:37:05,800 connectionpool.py:695] Starting new HTTPS connection (1): api.twitter.com
ERROR 2014-08-24 10:37:06,175 webapp2.py:1528] 'NoneType' object has no attribute 'wrap_socket'
Traceback (most recent call last):
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/Users/krishna/google-cloud-sdk/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/main.py", line 50, in post
tweetTextCotainer = THandler.getTweetsText()
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/main.py", line 82, in getTweetsText
access_token_secret = self.access_token_secret
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/TwitterSearch/TwitterSearch.py", line 63, in __init__
self.authenticate(verify)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/TwitterSearch/TwitterSearch.py", line 83, in authenticate
r = requests.get(self._base_url + self._verify_url, auth=self.__oauth, proxies=self.__proxy)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/api.py", line 55, in get
return request('get', url, **kwargs)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/sessions.py", line 574, in send
r = adapter.send(request, **kwargs)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/adapters.py", line 345, in send
timeout=timeout
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connectionpool.py", line 516, in urlopen
body=body, headers=headers)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connectionpool.py", line 304, in _make_request
self._validate_conn(conn)
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connectionpool.py", line 722, in _validate_conn
conn.connect()
File "/Users/krishna/Documents/DATASCI/twitterapi/analyzetweets/requests/packages/urllib3/connection.py", line 164, in connect
self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)
AttributeError: 'NoneType' object has no attribute 'wrap_socket'
For posterity (full discussion available on GitHub):
The "ssl" library appeared to have issues with import, thus ssl = None.
Updating the app.yaml helped.
libraries:
- name: ssl
version: latest
I have to classes comment and report:
class comment(ndb.Model):
date =ndb.StringProperty()
title=ndb.StringProperty()
name=ndb.StringProperty()
content=ndb.TextProperty()
class report(ndb.Model):
comments=ndb.StructuredProperty(comment,repeated=True)
date=ndb.StringProperty()
title=ndb.StringProperty()
content=ndb.BlobKeyProperty()
images=ndb.BlobKeyProperty(repeated=True)
images_urls=ndb.StringProperty(repeated=True)
so i declare comments (in the report class) as ndb.StructuredProperty ,then when i get the comment from the user i append it to the comments in this way:
class add(webapp2.RequestHandler):
def post(self):
key_url=self.request.get("key")
key=ndb.Key(urlsafe=key_url)
report=key.get()
title=self.request.get("title")
name=self.request.get("name")
date=self.request.get("date")
content=self.request.get("content")
new_comment=comment(date=date,title=title,name=name,content=content)
report.comments.append(new_comment)
report.put()
self.redirect('/comments?'+urllib.urlencode({"key":key_url}))
actually when I deploy the project it is work fine, but after a while maybe 30 minute it fail , it is weird ! I get this error message:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/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~newseltira/1.374704102870871150/upload_comment.py", line 64, in post
report.put()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3339, in _put
return self._put_async(**ctx_options).get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3351, in _put_async
self._prepare_for_put()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3233, in _prepare_for_put
prop._prepare_for_put(self)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 2411, in _prepare_for_put
values = self._get_base_value_unwrapped_as_list(entity)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1135, in _get_base_value_unwrapped_as_list
wrapped = self._get_base_value(entity)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1123, in _get_base_value
return self._apply_to_values(entity, self._opt_call_to_base_type)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1295, in _apply_to_values
value[:] = map(function, value)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1177, in _opt_call_to_base_type
value = _BaseValue(self._call_to_base_type(value))
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1198, in _call_to_base_type
return call(value)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1274, in call
newvalue = method(self, value)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 2273, in _validate
(self._modelclass.__name__, value))
BadValueError: Expected comment instance, got comment(content=u'fdsfd ds dsfdsf d', date=u'11/03/2014 03:07:25', name=u'dsfdsf', title=u'dsfdsf')
You said when I asked if you had the class defined elsewhere - you said "yes actually i have , but i am sure that all of them are the same , i do copy paste"
There's your answer.
You should never define the class in more than one place, because if they are imported in different orders you will have problems when doing comparisons.
this is what the stack trace is telling you with
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 2273, in _validate
(self._modelclass.__name__, value))
BadValueError: Expected comment instance, got comment(content=u'fdsfd ds dsfdsf d', date=u'11/03/2014 03:07:25', name=u'dsfdsf', title=u'dsfdsf')
the classes for comment don't match
When building projects your should always adher to the principal of DRY (don't repeat yourself).
Put all your classes in one file and then import them where ever you need to use them.
In this case the validation routine is comparing the classes and whilst they may defined identically they are different entities.
I'm getting a deadlineexceedederror when trying to create a kml file by a cron that starts a task. The error message is
2012-01-30 16:07:47.902 /createkml/ 500 5012ms 0kb AppEngine-Google; (+http://code.google.com/appengine)
0.1.0.2 - - [30/Jan/2012:10:07:47 -0800] "POST /createkml/ HTTP/1.1" 500 0 "http://www.koolbusiness.com/createkmltask/" "AppEngine-Google; (+http://code.google.com/appengine)" "www.koolbusiness.com" ms=5013 cpu_ms=3305 api_cpu_ms=295 cpm_usd=0.091855 queue_name=default task_name=7177535986681131286 instance=00c61b117cf890b99ca52a6b9e7c5f048e72
I 2012-01-30 16:07:42.959
creating file
E 2012-01-30 16:07:47.853
ApplicationError: 5
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~montaoproject/gralumo.356457066048686089/main.py", line 1575, in post
result = urlfetch.fetch(url)
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 263, in fetch
return rpc.get_result()
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 592, in get_result
return self.__get_result_hook(self)
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 371, in _get_fetch_result
raise DeadlineExceededError(str(err))
DeadlineExceededError: ApplicationError: 5
My code is
class CreateKMLTask(webapp2.RequestHandler):
def get(self):
logging.info('creating KML task')
taskqueue.add(url=r'/createkml/')
self.redirect('/')
class CreateKMLHandler(webapp2.RequestHandler):
def post(self):
# Create the file
logging.info('creating file')
file_name = \
files.blobstore.create(mime_type='application/octet-stream')
url = 'http://montaoproject.appspot.com/list.kml'
result = urlfetch.fetch(url)
if not result.content:
return
# Open the file and write to it
logging.info('opening file')
with files.open(file_name, 'a') as f:
f.write(result.content)
# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Get the file's blob key
logging.info('getting blob key of file')
blob_key = files.blobstore.get_blob_key(file_name)
logging.info('new blob key:'+str(blob_key))
im = Image.get_by_id(4468185)
im.primary_image = blob_key
im.put()
logging.info('new image key:'+str(im.primary_image))
logging.info('finished KML handling and put image')
webapp2.Route(r'/createkml/', handler=CreateKMLHandler,
name='createkml'),
webapp2.Route(r'/createkmltask/', handler=CreateKMLTask,
name='createkmltask')
My cron.yaml:
cron:
- description: daily mailout
url: /report/daily
schedule: every 24 hours
- description: daily mailout
url: /report/montaodaily
schedule: every 24 hours
- description: refresh kml
url: /createkmltask/
schedule: every 24 hours
What I'm trying to do is refresh to KML file to a new blob that has the same File ID as before so the call will be the same. What can I do to resolve my timeout problem? I think it should work.
Thanks
This timeout is fetching the url; you can see this in the stack trace. The fetch function defaults to a 5-second timeout.
The URL Fetch docs say you can increase the timeout by passing deadline as an additional argument. For example, deadline=60 would give you a 60-second timeout.
So, try result = urlfetch.fetch(url, deadline=60)