Error 'int' object has no attribute 'get' - django

This one is really confusing me. I am reading a excel file into my python script. When I run the script with about 9 rows it runs perfectly. When I run it with 10 rows it gives me this error. I looked the error up and it seems the solution is to use HttpResponse. I am already using the HttpResponse.
io = BytesIO()
writer = ExcelWriter(io)
data.to_excel(writer, 'Results', index=False)
data2.to_excel(writer, 'Suggestions', index=False)
writer.save()
rFile = io.getvalue()
response = HttpResponse(rFile ,content_type='application/ms-excel')
response['Content-Disposition'] = f'attachment; filename={FilePath}.xlsx'
return response
return render(request, 'home.html')
Here is the error
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/page_objects/
Django Version: 3.1.2
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
Exception Type: AttributeError at /page_objects/
Exception Value: 'int' object has no attribute 'get'
If you think any other part of my code would be useful to see let me know and I will edit it in.

I overestimated my ability and ensured myself that the error had to do with the return response part of my code. I found some QOL for my code I left behind that did not work that was causing the error. Thank you everyone for trying to help.

Related

How generate a pdf file with django-wkhtmltopdf on IIS 7.5 - 8

I use django-wkhtmltopdf to generate pdfs in my webapp, Works fine using the django integrate server, but when I use IIS 7.5 or 8 gives me this error: WindowsError [Error 6] The handle is invalid
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8006/blabla/pdf/10/
Django Version: 1.8.5
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'NuevoTicket',
'crispy_forms',
'wkhtmltopdf',
'ckeditor',
'ckeditor_uploader')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
164. response = response.render()
File "C:\Python27\lib\site-packages\django\template\response.py" in render
158. self.content = self.rendered_content
File "C:\Python27\lib\site-packages\wkhtmltopdf\views.py" in rendered_content
78. cmd_options=cmd_options
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template
159. cmd_options=cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf
121. return wkhtmltopdf(pages=[filename], **cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf
109. return check_output(ck_args, **ck_kwargs)
File "C:\Python27\lib\subprocess.py" in check_output
566. process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py" in __init__
702. errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py" in _get_handles
857. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Exception Type: WindowsError at /blabla/pdf/10/
Exception Value: 6 The handle is invalid
Finally got it, thank's to n1b0r. I have to update the check_out method in python27/lib/subprocess.py like this
from:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
to:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
kwargs.pop('stderr', None)
process = Popen(stdout=PIPE, stderr=PIPE, stdin=PIPE, *popenargs, **kwargs)
That make it works in IIS but gives an error if use the django integrate server.
I used to have the same problem. Add the option quiet to the pdfkit and also try to modify the file configuration.py from pdfkit
options = {'quiet': ''}
pdfkit.from_file('in.html', 'out.pdf',options = options)
configuration.py
from this:
self.wkhtmltopdf = subprocess.Popen(['where','wkhtmltopdf'],stdout=subprocess.PIPE).communicate()[0].strip()
to:
self.wkhtmltopdf = subprocess.Popen(['which','wkhtmltopdf'],stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0].strip()

iterator should return strings, not bytes (did you open the file in text mode?) while uploading csv in django

I want to upload csv file and store in database. when I click the submit button I get the following error
Environment:
Request Method: POST
Request URL: http://localhost:8000/csv
Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.admindocs',
'world',
'pft',
'wms',
'djgeojson',
'html5',
'geoexplorer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\views.py" in add_multiple_accounts
95. csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\utils.py" in handle_uploaded_file
24. if not valid_fields_method(data.fieldnames):
File "C:\Python34\lib\csv.py" in fieldnames
96. self._fieldnames = next(self.reader)
Exception Type: Error at /csv
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)
my handle file upload function is below-utils.py
def handle_uploaded_file(file, valid_fields_method, record_creation_function):
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
if not valid_fields_method(data.fieldnames):
return False, -1
result, rows_error = record_creation_function(data)
return result, rows_error
I'm using django 1.9 and python 3.4. Please help ! I'm struggling for past 2 days.
TL;DR:
Change this:
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
To this:
file.seek(0)
data = csv.DictReader(codecs.iterdecode(file, 'utf-8'))
(By the way, I'd check if seek(0) is really needed.)
Explanation:
You have understood that you need to decode the contents from your file, which is correct. However, to do so, you are using dialect, which is wrong.
dialect is not meant for this kind of stuff. Also, it should be a name registered via csv.register_dialect(), not an arbitrary iterator. But anyhow, dialects can't help you here.
Instead, you should pass the decoded stream directly to DictReader.

TypeError in Django after attempting to write data to MySQL using Django Models

I am trying to write data to MySQL DB using models in django but I am getting TypeError. I have failed to identify the problem. I have attached the errot summary, traceback and the lines of code generating the bug. Please help me identify the problem
TypeError at /httptester/670747/
'str' object is not callable
Request Method: POST Request URL: http://127.0.0.1:8000/httptester/670747/ Django Version: 1.5.12 Exception Type: TypeError Exception Value:
'str' object is not callable
Exception Location: /home/ronchino/deltasms/entry.py in handle, line 59 Python Executable: /home/ronchino/deltasms-venv/bin/python Python Version: 2.7.3 Python Path:
['/home/ronchino/deltasms', '/home/ronchino/deltasms-venv/lib/python2.7', '/home/ronchino/deltasms-venv/lib/python2.7/plat-linux2', '/home/ronchino/deltasms-venv/lib/python2.7/lib-tk', '/home/ronchino/deltasms-venv/lib/python2.7/lib-old', '/home/ronchino/deltasms-venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages']
Server time: Mon, 26 Jan 2015 10:14:12 -0600
TRACEBACK Environment:
Request Method: POST Request URL: http://127.0.0.1:8000/httptester/670747/
Django Version: 1.5.12 Python Version: 2.7.3 Installed Applications: ('model', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django_nose', 'django_tables2', 'selectable', 'south', 'rapidsms', 'rapidsms.backends.database', 'rapidsms.contrib.handlers', 'rapidsms.contrib.httptester', 'rapidsms.contrib.messagelog', 'rapidsms.contrib.messaging', 'rapidsms.contrib.registration', 'rapidsms.contrib.default') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback: File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
113. response = callback(request, *callback_args, **callback_kwargs) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/contrib/httptester/views.py" in message_tester
70. storage.store_and_queue(identity, cd["text"]) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/contrib/httptester/storage.py" in store_and_queue
39. receive(text, connection) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/router/api.py" in receive
40. router.receive_incoming(message) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/router/blocking/router.py" in receive_incoming
124. self.process_incoming(msg) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/router/blocking/router.py" in process_incoming
135. continue_processing = self.process_incoming_phases(msg) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/router/blocking/router.py" in process_incoming_phases
165. handled = func(msg) File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/contrib/handlers/app.py" in handle
33. if handler.dispatch(self.router, msg): File "/home/ronchino/deltasms-venv/local/lib/python2.7/site-packages/rapidsms/contrib/handlers/handlers/pattern.py" in dispatch
74. cls(router, msg).handle(*match.groups()) File "/home/ronchino/deltasms/entry.py" in handle
59. p2 = entry(full_name=fullname.title(), mobile_number=sender, address=address.title(), citytown=cityortown.title(), creation_datetime=date, combination=combination, entry_code=entryref)
Exception Type: TypeError at /httptester/670747/ Exception Value: 'str' object is not callable
CODE:
entry = '%32x' % random.getrandbits(32*5)
entryref = 'ENT' + entry[2] + entry [4] + entry[6] + entry[8] + entry [10] + entry[12] + entry[14] + entry [16] + entry[18] + entry[20]
#Add entry
try:
p2 = entry(full_name=fullname.title(), mobile_number=sender, address=address.title(), citytown=cityortown.title(), creation_datetime=date, combination=combination, entry_code=entryref)
p2.save()

django: why do i cannot store twitter.Twitter object into session

I created a twitter.Twitter object, but cannot store it into session. Following is my code.
t = twitter.Twitter(auth=twitter.OAuth(consumer_key, consumer_secret,
oauth_token, oauth_secret))
request.session['t'] = t
but if I store a string like
request.session['t'] = 't'
it works, why? because the twitter#Twitter object is not a serializable object? How can I avoid authenticating each time when I need a twitter#Twitter object? Following is the django trace.
Django Version: 1.3.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproj.myapp']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
178. response = middleware_method(request, response)
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/middleware.py" in process_response
36. request.session.save()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/file.py" in save
121. os.write(output_file_fd, self.encode(session_data))
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py" in encode
93. pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
File "/usr/lib/python2.6/site-packages/twitter-1.9.0-py2.6.egg/twitter/api.py" in __call__
173. return self._handle_response(req, uri, arg_data)
File "/usr/lib/python2.6/site-packages/twitter-1.9.0-py2.6.egg/twitter/api.py" in _handle_response
198. raise TwitterHTTPError(e, uri, self.format, arg_data)
Exception Type: TwitterHTTPError at /tool/log_in/
Exception Value:
Exactly as you guessed, you can only store pickleable objects.
From the docs
The session dictionary should accept any pickleable Python object. See the pickle module for more information.

Type Error: character mapping must return integer, None or unicode

I am trying to fetch information from linkedin but I keep getting the following error?
I have searched around but the fix I saw was only for those getting the error when using djangopiston. Can anyone help me fix this?
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/jobs/1/match/
Django Version: 1.3.1
Python Version: 2.7.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.flatpages',
'django.contrib.admin',
'django.contrib.staticfiles',
'compress',
'south',
'filer',
'easy_thumbnails',
'registration',
'socialregistration',
'socialregistration.contrib.facebook',
'socialregistration.contrib.twitter',
'socialregistration.contrib.linkedin',
'socialregistration.contrib.openid',
'privatebeta',
'api',
'profiles',
'jobs',
'misc']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'socialregistration.contrib.facebook.middleware.FacebookMiddleware',
'socialregistration.contrib.linkedin.middleware.LinkedInMiddleware',
'misc.middleware.SubdomainMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')
Traceback:
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "jobs/views.py" in match
60. matches = linkedin_api.get_connections(fields=['headline', 'summary',]).encode('utf-8')
File "../lib/linkedin/linkedin.py" in get_connections
291. response = self._do_normal_query(raw_url)
File "../lib/linkedin/linkedin.py" in _do_normal_query
757. signature_dict, self._access_token_secret, method, update=False)
File "../lib/linkedin/linkedin.py" in _calc_signature
789. hashed = hmac.new(self._calc_key(token_secret), signature_base_string, sha)
File "/usr/lib/python2.7/hmac.py" in new
133. return HMAC(key, msg, digestmod)
File "/usr/lib/python2.7/hmac.py" in __init__
72. self.outer.update(key.translate(trans_5C))
Exception Type: TypeError at /jobs/1/match/
Exception Value: character mapping must return integer, None or unicode
Its hard to tell but somewhere, either in urls.py and views.py are matches you should check the type of object being passed. It may not have expected value.
For instance /jobs/1/match, 1 maybe expected to be int but turns out be be str.
maybe because the text is being entered as unicode, try key.encode.('UTF-8')