I want to get name of the client that is trying to connect to server via Django, and I am stuck on this:
views.py
def home(request):
ime = request.META('REMOTE_HOST')
return HttpResponse('Welcome, %s.' %ime)
and error is:
Exception Type: TypeError
Exception Value: 'dict' object is not callable
**Traceback**
8. ime = request.META('REMOTE_HOST')
So, I don't get what the problem is.
I am still learning Django, btw.
request.META is a dictionary, so you need to access the REMOTE_HOST value with its key.
Change to:
ime = request.META['REMOTE_HOST'] # Note brackets not parens
Related
I have a question about an error that I am getting. I have a query that I am trying to send based on the Synapse Api for my project. I am currently trying to senda request taht creates a new user with the API. Every time I try to to send the request, I get a message that the User object doesnt have a create. Here is the error.
AttributeError at /setup_profile/
type object 'User' has no attribute 'create'
Request Method: POST
Request URL: http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: AttributeError
Exception Value:
type object 'User' has no attribute 'create'
Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in createUserSynapse, line 1104
Here is the current code that I have which will create the request to create a new user.
def createUserSynapse(request):
args = {
'email': 'hello#synapsepay.com',
'phone_number': '555-555-5555',
'legal_name': 'Hello McHello',
'note': ':)', # optional
'supp_id': '123abc', # optional
'is_business': True,
'cip_tag': 1
}
user = User.create(client, **args)
print(user)
Now i do know that with a normal query set, I have the object in the following format
User.objects.create(client, **args)
but when i do that I get an error that says
two parameters are being passed and 1 is requires so I think there is to many variables being passed... I am not sure where the error is coming from...
here is the error that I get when I use the User.objects.create(client, ** args)
TypeError at /setup_profile/
create() takes 1 positional argument but 2 were given
Request Method: POST
Request URL: http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: TypeError
Exception Value:
create() takes 1 positional argument but 2 were given
Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py in manager_method, line 127
UPDATED
The client needs to be passed into the api call and it contains the following:
import os
from synapse_pay_rest import Client
args = {
'client_id': 'client_id_...6YiBl',
'client_secret': 'client_secret_...kC3IF',
'fingerprint': '...dd48b',
'ip_address': '127.0.0.1',
'development_mode':True,
'logging':False
}
client = Client(**args)
Also, here is a github link to the api samples that were created by the api developers.
https://github.com/synapsepay/SynapsePayRest-Python
the client has to be passed with the api call
Create method has only key word arguments. Rewrite your code to this:
User.objects.create(client=client, **args)
UPDATE
I just figured out that you are using third party package. So you need to import User class like this from synapse_pay_rest import User as SynapseUser and use SynapseUser in your code: SynapseUser.create(clients, **argss)
I am using Ajax to make some requests from client to server, I am using DJango and I have used some Raw Sql queries before, but all of my fields was Int, varchar and a Decimal, for the last one I had an enconding problem, but I overrided the "default" property of Json and everything worked.
But that was before, now I have a query wich gives me Decimal and DateTime fields, both of them gave me enconding errors, the overrided "default" doesn't work now, thats why with this new one I used DjangoJSONEncoder, but now I have another problem, and its not an encoding one, I am using dictfetchall(cursor) method, recomended on Django docs, to return a dictionary from the Sql query, because cursor.fetchall() gives me this error: 'tuple' object has no attribute '_meta'.
Before I just sended that dictionary to json.dumps(response_data,default=default) and everything was fine, but now for the encoding I have to use the following: json.dumps(response_data,cls=DjangoJSONEncoder) and if I send the dictionary in that way, I get this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
And if I try to use the serializers, like this:
response_data2= serializers.serialize('json', list(response_data))
And later send response_data2 to dumps, I get this error:
'dict' object has no attribute '_meta'
This is the code for the MySql query:
def consulta_sql_personalizada(nombres,apellidos,puesto):
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("""select E.idEmpleado as id,CONCAT(Per.nombres_persona,' ',Per.apellidos_persona) as nombre,P.nombre_puesto as puesto,E.motivo_baja_empleado as motivo_baja,E.fecha_contratacion_empleado AS fecha_contratacion,E.fecha_baja_empleado as fecha_baja, SUM(V.total_venta) AS ventas_mes,E.fotografia_empleado as ruta_fotografia from Empleado as E
inner join Puesto as P on E.Puesto_idPuesto=P.idPuesto
inner join Venta as V on V.vendedor_venta=E.idEmpleado
inner join Persona as Per on E.Persona_idPersona=Per.idPersona
where (Per.nombres_persona like %s OR Per.apellidos_persona like %s OR E.Puesto_idPuesto=%s)
AND E.estado_empleado=1 AND V.estado_venta=1
AND
(YEAR(V.fecha_venta) = YEAR(Now())
AND MONTH(V.fecha_venta) = MONTH(Now()))""",[nombres,apellidos,puesto])
row = dictfetchall(cursor)
return row
And this is the last part of the view that makes the query and send it to ajax using json:
response_data=consulta_sql_personalizada(rec_nombres,rec_apellidos,rec_puesto)
return HttpResponse(
json.dumps(response_data,cls=DjangoJSONEncoder),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
What I want to know is, how can I parse the raw sql result to Json using that enconding?
Sorry, was my bad, i'm using JQuery ajax method, and in the "success" part I forgot to stop using json.parse to print the data in the console, the data was json already, that's why I had that line 1 column 1 error. My code worked exactly like it was posted here. If someone want to know how to make asynchronous requests, I followed this tutorial: Django form submissions using ajax
I am trying to setup an API using Django. In my views.py, I have this endpoint:
#api_view()
def update_label(request):
user_id = request.query_params['user_id']
date = datetime.strptime(request.query_params['date'], '%Y-%m-%dT%H:%M:%S.%f')
label_name = request.query_params['label_name']
value = request.query_params['value']
value = eval(value)
db_user_ctrl.update_label(date, user_id, label_name, value)
return Response({'status': 'SUCCESS'})
It updates some label in the database for some user. Multiple labels can be updated from this endpoint, some associate value with an integer, some associate value with a small dictionary e.g. {'item1':1,'item2':-1}. On the javascript side I use JSON.stringify(value) to format the value before sending it via a GET request. On the Django part, I can see the proper parameters have been recieved through the debugging interface. However I have the following error:
invalid literal for int() with base 10: '{"item1":-1}'
Associated with this line in my code:
value = request.query_params['value']
What is happening here? Why is he trying to casting the string into an integer?
EDIT 1:
Some more info on the stack trace:
.../venv/lib/python3.4/site-packages/django/core/handlers/base.py in get_response
.../venv/lib/python3.4/site-packages/django/core/handlers/base.py in get_response
.../venv/lib/python3.4/site-packages/django/views/decorators/csrf.py in wrapped_view
.../venv/lib/python3.4/site-packages/django/views/generic/base.py in view
.../venv/lib/python3.4/site-packages/rest_framework/views.py in dispatch
.../venv/lib/python3.4/site-packages/rest_framework/views.py in dispatch
.../venv/lib/python3.4/site-packages/rest_framework/decorators.py in handler
.../webapp/api/views.py in update_label
value = request.query_params['value']
Can you try
import json
json.loads(<query string value>)
The issue was quite sneaky, it was due to Gunicorn caching some files. In the old versions of views.py, I had value = int(request.query_params['value']). When I updated the code Gunicorn was still answering using the outdated cached files, hence the failure to cast a string into an int. I restarted Gunicorn and it's working now.
I am currently writing tests for our project, and I ran into an issue. We have this section of a view, which will redirect the user back to the page where they came from including an error message (that's being stored in the session):
if request.GET.get('error_code'):
"""
Something went wrong or the call was cancelled
"""
errorCode = request.GET.get('error_code')
if errorCode == 4201:
request.session['errormessage'] = _('Action cancelled by the user')
return HttpResponseRedirect('/socialMedia/manageAccessToken')
Once the HttpResponseRedirect kicks in, the first thing that the new view does is scan the session, to see if any error messages are stored in the session. If there are, we place them in a dictionary and then delete it from the session:
def manageAccessToken(request):
"""
View that handles all things related to the access tokens for Facebook,
Twitter and Linkedin.
"""
contextDict = {}
try:
contextDict['errormessage'] = request.session['errormessage']
contextDict['successmessage'] = request.session['successmessage']
del request.session['errormessage']
del request.session['successmessage']
except KeyError:
pass
We should now have the error message in a dictionary, but after printing the dictionary the error message is not there. I also printed the session just before the HttpResponseRedirect, but the session is an empty dictionary there as well.
This is the test:
class oauthCallbacks(TestCase):
"""
Class to test the different oauth callbacks
"""
def setUp(self):
self.user = User.objects.create(
email='test#django.com'
)
self.c = Client()
def test_oauthCallbackFacebookErrorCode(self):
"""
Tests the Facebook oauth callback view
This call contains an error code, so we will be redirected to the
manage accesstoken page. We check if we get the error message
"""
self.c.force_login(self.user)
response = self.c.get('/socialMedia/oauthCallbackFacebook/',
data={'error_code': 4201},
follow=True,
)
self.assertEqual('Action cancelled by the user', response.context['errormessage'])
It looks like the session can not be accessed or written to directly from the views during testing. I can, however, access a value in the session by manually setting it in the test by using the following bit of code:
session = self.c.session
session['errormessage'] = 'This is an error message'
session.save()
This is however not what I want, because I need the session to be set by the view as there are many different error messages in the entire view. Does anyone know how to solve this? Thanks in advance!
After taking a closer look I found the issue, it is in the view itself:
errorCode = request.GET.get('error_code')
if errorCode == 4201:
request.session['errormessage'] = _('Action cancelled by the user')
The errorCode variable is a string, and I was comparing it to an integer. I fixed it by changing the second line to:
if int(errorCode) == 4201:
I am editing the Runwithfriends FB sample app to build one of my own. It was working fine and I was making a few changes here and there. I took a break from it for about a fortnight but now when I try to access the app, I get a strange python error:
C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\app\main.py in init_facebook(self=<main.RecentRunsHandler object>)
316 user_id=facebook.user_id, friends=friends,
317 access_token=facebook.access_token, name=me[u'name'],
=> 318 email=me.get(u'email'), picture=me[u'picture'])
319 user.put()
320 except KeyError, ex:
<..some portion clipped..>
class 'google.appengine.api.datastore_errors.BadValueError'>: Property picture must be a str or unicode instance, not a dict
args = ('Property picture must be a str or unicode instance, not a dict',)
message = 'Property picture must be a str or unicode instance, not a dict'"
I know this is a very generic error but its pointing to the following code. This code has always been there and I have never touched it. I really do not know where else to look now - I have searched exhaustively but couldnt find a clue. Sorry, if this is still too broad but I would be glad if you can tell me what other info can I provide to debug this :-(
def init_facebook(self):
"""Sets up the request specific Facebook and User instance"""
facebook = Facebook()
user = None
# initial facebook request comes in as a POST with a signed_request
if u'signed_request' in self.request.POST:
facebook.load_signed_request(self.request.get('signed_request'))
# we reset the method to GET because a request from facebook with a
# signed_request uses POST for security reasons, despite it
# actually being a GET. in webapp causes loss of request.POST data.
self.request.method = u'GET'
self.set_cookie(
'u', facebook.user_cookie, datetime.timedelta(minutes=1440))
elif 'u' in self.request.cookies:
facebook.load_signed_request(self.request.cookies.get('u'))
# try to load or create a user object
if facebook.user_id:
user = User.get_by_key_name(facebook.user_id)
if user:
# update stored access_token
if facebook.access_token and \
facebook.access_token != user.access_token:
user.access_token = facebook.access_token
user.put()
# refresh data if we failed in doing so after a realtime ping
if user.dirty:
user.refresh_data()
# restore stored access_token if necessary
if not facebook.access_token:
facebook.access_token = user.access_token
if not user and facebook.access_token:
me = facebook.api(u'/me', {u'fields': _USER_FIELDS})
try:
friends = [user[u'id'] for user in me[u'friends'][u'data']]
user = User(key_name=facebook.user_id,
user_id=facebook.user_id, friends=friends,
access_token=facebook.access_token, name=me[u'name'],
email=me.get(u'email'), picture=me[u'picture'])
user.put()
except KeyError, ex:
pass # ignore if can't get the minimum fields
self.facebook = facebook
self.user = user
Might have to do with the October 2012 Breaking Changes, quote:
/picture connection will return a dictionary when a callback is specified
We will start returning a dictionary containing the fields url, height, width, and is_silhouette when accessing the /picture connection for an object and specifying a callback property. Currently we just return the picture URL as a string.
So at this point in your code, where you are currently using picture=me[u'picture'], try accessing the url property of the picture dictionary instead. (If it has one; I can’t tell you for sure if this is applicable, since I don’t know if your code would be considered as having specified a callback property.)
If my assumption is correct, you could also enable the migration as described in the roadmap; but that will only make your app work in the old way until Oct. 3rd, so probably better to try and fix it right away.
This is the way to get the picture:
picture=me[u'picture'][u'data'][u'url']