maximum recursion depth exceeded in django - django-forms

**i have occured error when i logout then occure this error maximum recursion depth exceeded........................................................................................................... **
template.html
RecursionError at /logout/
maximum recursion depth exceeded
Request Method: GET
Request URL: http://127.0.0.1:8000/logout/
Django Version: 3.0.6
Exception Type: RecursionError
Exception Value:
maximum recursion depth exceeded
Exception Location: C:\Users\Aqib\Desktop\Python Djnago\vscode projects\thumbsap\account\views.py in logout, line 213
Python Executable: C:\Users\Aqib\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.3
Python Path:
['C:\\Users\\Aqib\\Desktop\\Python Djnago\\vscode projects\\thumbsap',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\Aqib\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin']
Server time: Wed, 3 Jun 2020 04:35:00 +0530
Traceback Switch to copy-and-paste view
C:\Users\Aqib\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py in inner
response = get_response(request) …
projects\thumbsap\account\views.py in logout
logout(request) …
views.py
def logout(request):
logout(request)
messages.SUCCESS(request,"your successfully logged out")
return render(request,'home/login.html')
return HttpResponse("Logged Out Successfully")

look at the first line of your logout function ...
def logout(request):
logout(request)
.....
All this is doing is calling itself with no way of stopping.
I assume that the call to logout was intended to call django.contrib.auth.logout, and thereofre you have something like this at the top of your module :
from django.contrib.auth import logout
But the problem is when you do
def logout(request)
....
That defines a new logout names, and it replaces what you imported.
You have two solutions :
rename your logout(request) function, but that will mean changing your url.py, so the new function is invoked
Change the import to something else (using an alias) so that logout name that is imported isn't overriten
If you opt for option 2, your code will become:
from django.contrib.auth import logout as dca_logout
....
def logout(request):
dca_logout(request)
....
Using a different name for the django.contrib.auth.login will ensure that your logout function doesn't makes the name you import.

Related

How to correct TypeError with choices() missing 1 required positional argument: 'population'

I want list of entries to display when calling the random page function but I keep getting this error choices() missing 1 required positional argument: 'population'.
I had this problem due a typo recently.
Aparently you are using the recommended 'secrets' PNG and not 'random' pseudoPNG. I had the following code:
#!/usr/bin/python3
"""
Will get 10 random letters...
from the lowercase abcdefghijklmnopqrstuvwxyz
"""
import string
import secrets
response = secrets.SystemRandom.choices(string.ascii_lowercase, k=10)
print(response)
But secrets.SystemRandom is a class, so I just changed it to secrets.SystemRandom() and the issue was fixed.
Fixed code:
#!/usr/bin/python3
"""
Will get 10 random letters...
from the lowercase abcdefghijklmnopqrstuvwxyz
"""
import string
import secrets
response = secrets.SystemRandom().choices(string.ascii_lowercase, k=10)
print(response)

How to print Graphene-Django / Graphene-Python Exceptions to the Console for Debugging?

When a GraphQL Error occurs, I cannot easily know where it occured. I have to spend unnecessary time trying to track it down. How do I get a Traceback printed in the console of my text editor?
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.
Does anyone have a different or better way of doing it?
Example usage of the print_graphql_errors function:
from django.conf.settings import DEBUG
result = schema.execute(
mutation_str, context_value=request, variable_values=variable_values
)
if result.errors is None:
return self.handle_success(result)
if DEBUG:
print_graphql_errors(result.errors)
return self.handle_failure(result)
The print_graphql_errors function:
from traceback import print_tb
from django.conf.settings import DEBUG
def print_graphql_errors(errors, raise_error=False):
if not DEBUG:
raise Exception(
'DevError: This function should not be called in production'
)
assert errors, 'DevError: The "errors" parameter cannot be None'
print_after = []
current_error = None
print('######################################################################')
print('Manually Generated Traceback (with the print_graphql_errors function):')
print(f'There are {len(errors)} errors:')
for i, error in enumerate(errors):
print(f'{i + 1}) ', error)
print('######################################################################')
for error in errors:
current_error = error
# FYI: This object has these attributes: (example attribute values)
# tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
# tb_lasti 16
# tb_lineno 447
# tb_next <traceback object at 0x000002DDBAFBA388>
# print('error.locations:', error.locations)
# print('error.positions:', error.positions)
try:
print_tb(error.stack)
except AttributeError as e:
print(e.__traceback__)
print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
print_after.append(error)
if len(print_after):
print('###################################################################')
print(f'Number of errors without the "stack" attribute: {len(print_after)}')
print('###################################################################')
if raise_error:
for error in print_after:
raise error
raise current_error

Problem with get_children() method when using TreeManager. Wrong result

I have encountered an strange problem with the use of TreeManager
Here is my code:
# other imports
from mptt.models import MPTTModel, TreeForeignKey
from mptt.managers import TreeManager
class SectionManager(TreeManager):
def get_queryset(self):
return super().get_queryset().filter(published=True)
class Section(MPTTModel):
published = models.BooleanField(
default=True,
help_text="If unpublished, this section will show only"
" to editors. Else, it will show for all."
)
objects = TreeManager()
published_objects = SectionManager()
When I test it. I get the following correct results:
# show all objects
Section.objects.count() # result is correct - 65
Section.objects.root_nodes().count() # result is correct - 12
# show published objects, just one is not published.
Section.published_objects.count() # result is correct - 64
Section.published_objects.root_nodes().count() # result is corrct - 12
But one child of the roots is unpublished and it does not show in the results. Here is the test:
for root in Section.objects.root_nodes():
print(f"root_section_{root.id} has {root.get_children().count()} children")
# results ...
root_section_57 has 13 children # correct - 13 items
# ... more results
for root in Section.published_objects.root_nodes():
print(f"root_section_{root.id} has {root.get_children().count()} children")
# results ...
root_section_57 has 13 children # WRONG - should be only 12 children
# ... more results
I may not understand something, or I may have hit a bug??
Any ideas?
NOTE: This issue has been posted on the django-mptt github issues page at: https://github.com/django-mptt/django-mptt/issues/689
https://github.com/django-mptt/django-mptt/blob/master/mptt/managers.py
You override wrong function call. root_nodes() call ._mptt_filter()
#delegate_manager
def root_nodes(self):
"""
Creates a ``QuerySet`` containing root nodes.
"""
return self._mptt_filter(parent=None)
And your _mptt_filter does not got any given qs.
#delegate_manager
def _mptt_filter(self, qs=None, **filters):
"""
Like ``self.filter()``, but translates name-agnostic filters for MPTT
fields.
"""
if qs is None:
qs = self
return qs.filter(**self._translate_lookups(**filters))
Now you need to customized based on your use case.
Hope it can be some help

Python Time based rotating file handler for logging

While using time based rotating file handler.Getting error
os.rename('logthred.log', dfn)
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process
config :
[loggers]
keys=root
[logger_root]
level=INFO
handlers=timedRotatingFileHandler
[formatters]
keys=timedRotatingFormatter
[formatter_timedRotatingFormatter]
format = %(asctime)s %(levelname)s %(name)s.%(functionname)s:%(lineno)d %
(output)s
datefmt=%y-%m-%d %H:%M:%S
[handlers]
keys=timedRotatingFileHandler
[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=timedRotatingFormatter
args=('D:\\log.out', 'M', 2, 0, None, False, False)
Want to achieve time based rotating file handler and multiple process can write same log file.In python,I didn't find any thing which can help to resolve this issue.
I have read discussion on this issue (python issues).
Any suggestion which can resolve this issue.
Found the solution : Problem in Python 2.7 whenever we create child Process then file handles of parent process also inherited by child process so this is causing error. We can block this inheritance using this code.
import sys
from ctypes import windll
import msvcrt
import __builtin__
if sys.platform == 'win32':
__builtin__open = __builtin__.open
def __open_inheritance_hack(*args, **kwargs):
result = __builtin__open(*args, **kwargs)
handle = msvcrt.get_osfhandle(result.fileno())
if filename in args: # which filename handle you don't want to give to child process.
windll.kernel32.SetHandleInformation(handle, 1, 0)
return result
__builtin__.open = __open_inheritance_hack

GAE + Python2.7 + webapp2 + AJAX

Are there any tutorials or code examples related to AJAX implementation for GAE + Python2.7 + webapp2.
I have tried to follow instructions below:
http://code.google.com/appengine/articles/rpc.html
but I receive the following error:
Traceback (most recent call last):
File "E:\dev\workspace\test\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "E:\dev\workspace\test\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1101, in __call__
handler = self.handler(request, response)
TypeError: __init__() takes exactly 1 argument (3 given)
There is another similar discussion here:
Google App Engine Python Protorpc Error: __call__() takes exactly 1 argument (3 given)
heres is my code from Specialscope's example:
main.py
from BaseHandler import BaseHandler
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import logging
from google.appengine.api import files
from google.appengine.api import images
import json
import webapp2
class FileuploadHandler(BaseHandler):
def get(self):
blobstore.create_upload_url('/static')
context={}
self.render_response("uploader.html",**context)
class FileDownloadHandler(blobstore_handlers.BlobstoreUploadHandler,BaseHandler):
def post(self):
upload_files=self.request.POST
#image=upload_files['file']
logging.error(upload_files)
keys=upload_files.keys()
imageurls=[]
for key in keys:
if key.find("uploadimage")!=-1:
image=upload_files[key]
file_name=files.blobstore.create(mime_type='image/jpg')
with files.open(file_name,'a') as f:
f.write(image.value)
files.finalize(file_name)
blob_key=files.blobstore.get_blob_key(file_name)
imageurls.append(images.get_serving_url(blob_key))
context={}
context['imagelinks']=imageurls
self.response.write(json.dumps(context))
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
BaseHandler.py
import webapp2
import os
from webapp2_extras import jinja2
from google.appengine.ext import db
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
The stack trace suggests that you have a url mapping in your WSGIApplication that has a group in it, but there's no handler with the corresponding arguments.
If you have
(r'/foo/(\s+)/(\s+)', FooHandler),
then you need
class FooHandler(webapp2.RequestHandler):
def get(self, arg1, arg2):
...
The doc you're using pre-dates Python 2.7 support by several years. Were I in your position, I'd be tempted to get the app working first on Python 2.5, then port to 2.7.
The problem is here:
import webapp2
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
You can't use webapp2.WSGIApplication to construct your application, it doesn't understand protorpc. Instead, do this:
from protorpc.wsgi import service
app = service.service_mappings([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
])

Resources