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

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.

Related

Error 'int' object has no attribute 'get'

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.

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.

<Model> matching query does not exist

I've learned python django since three days ago .
I wanted to remove an field from model, so I put the '#' front of that field.
Then I started the server again, but it gave me such an error message
'Userprofile matching query does not exist' (Userprofile is the model which I made.)
How can I solve this problem. I'm just a totally new to django, so even it's not easy to question my problem. If the clue is not enough, please tell me what other information is need.
p.s here is the total error message.
Environment:
Request Method: GET
Request URL: h ttp://localhost:8000/
Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.admin',
'south',
'autocomplete_light',
'djcelery',
'asap_web',
'facebook',
'venue',
'notification',
'study',
'general',
'member',
'advertise')
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/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in __call__
89. return main()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in main
25. return process_request()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in process_request
53. return _call_proper_request_processor()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in _call_proper_request_processor
77. return getattr(self, method_name)(request, *self.args, **kwargs)
File "/home/jaehoon/PycharmProjects/studysearch/general/views.py" in process_get_request
19. if user.is_authenticated() and user.get_profile().is_required_more_info:
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in get_profile
441. self._state.db).get(user__id__exact=self.id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get
307. self.model._meta.object_name)
Exception Type: DoesNotExist at /
Exception Value: UserProfile matching query does not exist.
The exception is DoesNotExist which is thrown when you use get to retrieve single instance but it does not exist. In your process_get_request view:
user.get_profile().is_required_more_info
is throwing this exception because there is no profile created for this user. Note that user.get_profile() is deprecated since django 1.5 and you should use OneToOne field or custom user model instead, from docs:
get_profile() Deprecated in Django 1.5: Deprecated since version 1.5:
With the introduction of custom User models, the use of
AUTH_PROFILE_MODULE to define a single profile model is no longer
supported. See the Django 1.5 release notes 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')