I have a file that sends a request to an API and retrieves information. Let's call this file get_info.py. I am now building a GUI that uses Django and the views.py file, with methods 'GET' and 'POST'.
I am now importing the function from get_info.py into views.py and using it as follows
from get_info import get_info
#api_view(['GET'])
def generate_route(request):
"""
:param request:
1. lat: posx
2. lng: pos,
3. r: radius in km
4. strategy,
5. edge_num,
6. deep,
:return:
"""
posx = request.query_params.get('lat', None)
posy= request.query_params.get('lng', None)
r= request.query_params.get('r', None)
strategy = request.query_params.get('strategy', None)
strategy = strategy if strategy else 3
edge_num = request.query_params.get('edge_num', None)
edge_num = edge_num if edge_num else 3
deep = request.query_params.get('deep', None)
deep = deep if deep else 3
print("BEFORE", posx, posy, r, strategy, edge_num, deep)
route = get_info(posx, posy, r)
print("AFTER", route)
if request.query_params.get('lat', None) is not None \
and request.query_params.get('lng', None) is not None \
and request.query_params.get('r', None) is not None:
return Response({}, status=status.HTTP_200_OK)
else:
return Response({
"Error": 'Need lat, lng, and r {}'.format(request.query_params.get('lat', None))
}, status=status.HTTP_400_BAD_REQUEST)
```
However, I get the response
> (u'BEFORE', u'112.34', u'14.55', u'300.3', 3, 3, 3)
Internal Server Error: /app/api/v1/get_info/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/home/user/Projects/app/views.py", line 750, in generate_route
route = get_info(posx, posy, r)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 466, in dispatch
request = self.initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 370, in initialize_request
parser_context=parser_context
File "/usr/local/lib/python2.7/dist-packages/rest_framework/request.py", line 159, in __init__
.format(request.__class__.__module__, request.__class__.__name__)
AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `__builtin__.unicode`.
But when I use from django.http import HttpRequest to build my request, it tells me 'maximum depth exceeded'.
The get_info method is quite long, but in a nutshell it looks like this:
def get_info(posx, posy, r, strategy=3, edge_num=0.8, deep=0):
req_url = "http://api.map.baidu.com/direction/v2/driving?origin=posx..."
trip = requests.get(req_url).json()
return trip
When I run this get_info method in my python shell, it returns the desired trip.
If you look closely rest framework is the one which is causing the problem, If the getinfo is an APIView then it might need request as its first argument not posx which is a string.
Related
I have problem with google auth. Steps to reproduce problem:
Register password account
Try to log in with google auth
Get 500 answer
Traceback:
Internal Server Error: /api/v1/auth/google/
Traceback (most recent call last):
File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 54, in dispatch
return super().dispatch(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/andrew/Documents/pets_backend/project/api_v1/views/social.py", line 77, in post
response = super().post(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 125, in post
self.serializer.is_valid(raise_exception=True)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 422, in run_validation
value = self.validate(value)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/registration/serializers.py", line 151, in validate
complete_social_login(request, login)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login
return _complete_social_login(request, sociallogin)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 172, in _complete_social_login
ret = _process_signup(request, sociallogin)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 22, in _process_signup
url = reverse("socialaccount_signup")
File "/home/andrew/.local/lib/python3.10/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'socialaccount_signup' not found. 'socialaccount_signup' is not a valid view function or pa
ttern name.
"POST /api/v1/auth/google/ HTTP/1.1" 500 184486
I added to configs
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
SOCIALACCOUNT_EMAIL_REQUIRED = False
SOCIALACCOUNT_QUERY_EMAIL = False
but not worked.
When I try to add an url attribute to my model I get this error:
AttributeError: 'collections.OrderedDict' object has no attribute 'pk'
These are the codes I use. I tried a lot of things but just get an error with everything I try..
Serializer:
class GroupPatchSerializer(serializers.ModelSerializer):
linked_sites = serializers.ListField()
name = serializers.CharField(required=False)
url = serializers.HyperlinkedIdentityField(
view_name="group-detail", lookup_url_kwarg="group_pk"
)
class Meta:
model = Group
fields = ("id", "url", "name", "linked_sites")
def validate_linked_sites(self, sites):
** code **
return sites
# noinspection PyMethodMayBeStatic
def validate_name(self, name):
** code **
return name
view:
def patch(self, request, group_pk):
"""
Add site to group, change an existing group's name.
-id: The group's id
"""
user = request.user
group_id = int(group_pk)
group = Group.objects.filter(pk=group_id).first()
# Update the group
serializer_class = self.get_serializer_class()
serializer = serializer_class(
data=self.request.data,
context={"request": request, "user_pk": user.id, "group_id": group_id},
)
test-class:
def test_ok_authorized_access(self):
# Login the user
self.client.force_login(self.user_1)
UserSiteFactory(user=self.user_1, site=self.test_site_3)
# Get the url
url = reverse("group-detail", kwargs={"group_pk": self.test_group_1.pk})
# New group name
new_name = "New group name"
sites = [self.test_site_3.pk]
# Execute the patch operation
response = self.client.patch(
url, data={"name": new_name, "linked_sites": sites}
)
# Test if there was no error
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Test if the group was renamed
group = Group.objects.all().filter(pk=self.test_group_1.pk).first()
self.assertEqual(group.name, new_name)
stacktrace
Traceback (most recent call last):
File "/opt/project/backend/groups/tests/test_group_patch.py", line 45, in test_ok_authorized_access
url, data={"name": new_name, "linked_sites": sites}
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 310, in patch
path, data=data, format=format, content_type=content_type, **extra)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 215, in patch
return self.generic('PATCH', path, data, content_type, **extra)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 232, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 283, in request
return super().request(**kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 235, in request
request = super().request(**kwargs)
File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/opt/project/backend/groups/views/group_detail_view.py", line 108, in patch
return Response(serializer.data, status=status.HTTP_200_OK)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 559, in data
ret = super().data
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 263, in data
self._data = self.to_representation(self.validated_data)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 526, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.6/site-packages/rest_framework/relations.py", line 393, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "/usr/local/lib/python3.6/site-packages/rest_framework/relations.py", line 329, in get_url
lookup_value = getattr(obj, self.lookup_field)
AttributeError: 'collections.OrderedDict' object has no attribute 'pk'
From the DRF docs on HyperlinkedIdentityField:
lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
So you're setting lookup_url_kwarg directly, but you're not changing lookup_field, which is where your error is coming from. Because lookup_url_kwarg defaults to the same value as lookup_field, we can just use that:
class GroupPatchSerializer(serializers.ModelSerializer):
# code...
url = serializers.HyperlinkedIdentityField(
view_name="group-detail", lookup_field="group_pk"
)
# code...
I have a created a simple Python program, which will retrieve and add data to database based on the user input. I used POST method for this. The program is successfully working in Postman, but when I call the program from an iOS app using API call, the program is showing 500 error. The errors are in exception.py and base.py. My program is given below
#api_view(["POST"])
def mg_grt(request):
if request.method == 'POST':
name = request.POST['name']
word = name.lower()
greet = Greet.objects.filter(grett=word)
if greet != 0:
d = Resp(rsp=word)
d.save()
r_val = Resp.objects.all()
rt = random.choice(r_val)
return HttpResponse(rt)
else:
return HttpResponse("Sorry...I didn't understand")
else:
return HttpResponse("Bad Request")
The errors are:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/abijith/Test5/tgpi/views.py", line 21, in mg_grt
name = request.POST['name']
File "/Library/Python/2.7/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "u'name'"
[31/Aug/2018 10:20:45] "POST /grt/ HTTP/1.1" 500 14099
I'm trying to override the method save() of my model:
class Article(models.Model):
number = models.PositiveIntegerField(editable=False)
def save(self, *args, **kwargs):
if not self.pk: #means: if objects wasn't saved before
self.number = Article.objects.count() +1 #number is 1-based
super(Article, self).save(*args, **kwargs)
Now I tried to add a new article from the admin page. The error I get:
self.number = Article.objects.count() +1
NameError: name 'self' is not defined
What am I doing wrong?
Some optional information:
number is some kind of ID, to order the objects in my way but these IDs shouldn't be changed manually
number is not allowed to be empty or blank, so I have to set a value before saving the first time (that's what I'm trying with that code snippet)
When an object is saved, the default number should be equal to the number of all objects (after saving), in 1-based counting
to change the order of the objects admin actions will be used
The whole traceback
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 544, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 211, in inner
return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1509, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.5/contextlib.py", line 30, in inner
return func(*args, **kwds)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1449, in changeform_view
self.save_model(request, new_object, form, not add)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1007, in save_model
obj.save()
File "/media/[directory to my projects]/projects_actual/myproject/myapp/models.py", line 69, in save
seĺf.number = Article.objects.count() + 1
NameError: name 'seĺf' is not defined
[16/Apr/2017 11:07:00] "POST /admin/myapp/article/add/ HTTP/1.1" 500 121043
Do you miss some information?
I am creating the dynamic queryset using Q
while i am printing
build_query[:-1]
i am getting output
Q(owner_id=1)|Q(assigned_to=1)
but when using this in to
consultants = Consultant.objects.filter(*build_query[:-1])
getting an error too many values to unpack
i tried it with ** and without * still its not working.
when i check the type of
print type(build_query[:-1])
i am getting string type. Is the a main cause?
Traceback
Internal Server Error: /api/consultants/my_consultants/
Traceback (most recent call last):
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 85, in view
return self.dispatch(request, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/views.py", line 451, in dispatch
response = self.handle_exception(exc)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/views.py", line 448, in dispatch
response = handler(request, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/ckiller/consultants/api.py", line 170, in my_consultants
consultants = Consultant.objects.filter(*build_query[:-1])
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
Q(owner_id=1)|Q(assigned_to=1)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/query.py", line 691, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/query.py", line 709, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1331, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
consultants = Consultant.objects.filter(*build_query[:-1])
Did u try:
Consultant.objects.filter(*[build_query[:-1],])
args should be a list