MongoDB with Django: TypeError: Model instances without primary key value are unhashable - python-3.x

I'm trying to connect MongoDB with Django.
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': '<name>',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': f'mongodb+srv://{mongodb_username}:{mongodb_password}#{mongodb_cluster}/?retryWrites=true',
'uuidRepresentation': 'standard',
'waitQueueTimeoutMS': 30000
}
}
}
models.py
import uuid
from django.db import models
# Create your models here.
class ModernConnectUsers(models.Model):
user_id = models.UUIDField(primary_key=True, default=uuid.uuid4())
user_name = models.CharField(max_length=30, null=False)
The model has not been used anywhere for now.
python manage.py makemigrations && python manage.py migrate
outputs:
Migrations for 'modern_connect':
modern_connect/migrations/0003_alter_modernconnectusers_user_id.py
- Alter field user_id on modernconnectusers
Operations to perform:
Apply all migrations: admin, auth, contenttypes, modern_connect, sessions
Running migrations:
No migrations to apply.
Your models in app(s): 'modern_connect' have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 317, in handle
emit_post_migrate_signal(
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/sql.py", line 52, in emit_post_migrate_signal
models.signals.post_migrate.send(
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 176, in send
return [
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions
ctypes.add(ctype)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/db/models/base.py", line 597, in __hash__
raise TypeError("Model instances without primary key value are unhashable")
TypeError: Model instances without primary key value are unhashable
The only collection I'm currently using has a Primary Key, but for some reason - The program is falling for self.pk == None in Base.py which is raising this error. Solutions under other questions didn't help, so starting another question.

In your models.py, try importing the models from djongo.
from djongo import models
And for primary key I use
class User(models.Model):
_id = models.ObjectIdField()
But you can play around with uuid() and see if it works or not.

Related

InvalidClientTokenId error when trying to access SQS from Celery

When I try to connect to SQS using Celery, I'm not able to. The worker crashes with the following message:
[2022-10-28 14:05:39,237: CRITICAL/MainProcess] Unrecoverable error: ClientError('An error occurred (InvalidClientTokenId) when calling the GetQueueAttributes operation: The security token included in the request is invalid.')
Traceback (most recent call last):
File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/worker.py", line 203, in start
self.blueprint.start(self)
File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start
step.start(parent)
File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 365, in start
return self.obj.start()
File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/consumer/consumer.py", line 332, in start
blueprint.start(self)
File "/home/aditya/.local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start
step.start(parent)
File "/home/aditya/.local/lib/python3.10/site-packages/celery/worker/consumer/tasks.py", line 38, in start
c.task_consumer = c.app.amqp.TaskConsumer(
File "/home/aditya/.local/lib/python3.10/site-packages/celery/app/amqp.py", line 274, in TaskConsumer
return self.Consumer(
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 387, in __init__
self.revive(self.channel)
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 409, in revive
self.declare()
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/messaging.py", line 422, in declare
queue.declare()
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 606, in declare
self._create_queue(nowait=nowait, channel=channel)
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 615, in _create_queue
self.queue_declare(nowait=nowait, passive=False, channel=channel)
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/entity.py", line 643, in queue_declare
ret = channel.queue_declare(
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/transport/virtual/base.py", line 523, in queue_declare
return queue_declare_ok_t(queue, self._size(queue), 0)
File "/home/aditya/.local/lib/python3.10/site-packages/kombu/transport/SQS.py", line 633, in _size
resp = c.get_queue_attributes(
File "/home/aditya/.local/lib/python3.10/site-packages/botocore/client.py", line 514, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/home/aditya/.local/lib/python3.10/site-packages/botocore/client.py", line 938, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the GetQueueAttributes operation: The security token included in the request is invalid.
The credentials are correct, and my Cloud Admin insists that my credentials have these permissions.
If it helps, these are in my settings.py :
from urllib.parse import quote
CELERY_BROKER_URL = 'sqs://{access_key}:{secret_key}#'.format(
access_key=quote(env.str("AWS_ACCESS_KEY_ID"), safe=''),
secret_key=quote(env.str("AWS_SECRET_ACCESS_KEY"), safe=''),
)
CELERY_BROKER_TRANSPORT_OPTIONS = {
"region": "us-east-2",
"polling_interval": 60,
'sdb_persistence': False,
"predefined_queues":{
'myq': {
'url': 'https://sqs.us-east-2.amazonaws.com/164782647287/myq',
'access_key_id': env.str("AWS_ACCESS_KEY_ID"),
'secret_access_key': env.str("AWS_SECRET_ACCESS_KEY"),
},
}
}
CELERY_TASK_DEFAULT_QUEUE = 'myq'
I'm using the latest version of Celery and associated dependencies:
celery[sqs]==5.2.7

Upload file from Django app to IBM Cloud Object Storage

I'm trying to connect a django app to IBM COS and having trouble. I'm capturing user video and want to save the file to IBM COS and the user info to Postgres also hosted on IBM. I'm able to connect from both the terminal and my app to IBM COS and move files around, but am having trouble getting the default storage configured properly. I'm using django-storages, trying to adapt the AWS configurations for IBM but I must be missing something.
This code will save the file to IBM COS, but makes no entries in the DB. The problem may be in the configuration?
Also, I am not able to manually upload a file form the django admin panel - I get a similar traceback. Thanks in advance for any help.
settings.py
# IBM STORAGE CONFIG
IBM_API_KEY_ID = 'IBM_API_KEY_ID'
IAM_SERVICE_ID = 'IAM_SERVICE_ID'
ENDPOINT = 'https://s3.us-east.cloud-object-storage.appdomain.cloud'
IBM_AUTH_ENDPOINT = 'https://iam.bluemix.net/oidc/token'
SERVICE_INSTANCE_ID = 'SERVICE_INSTANCE_ID'
IBM_STORAGE_BUCKET_NAME = 'cloud-object-storage-3u-cos-standard-77w'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
models.py
class Video(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
videofilename=models.CharField(max_length=500)
videofile=models.FileField(upload_to="video/", null=True, verbose_name="")
def __str__(self):
return str(self.videofile)
views.py
class upload_to_ibm_auto(LoginRequiredMixin, CreateView):
model = Video
context_object_name = 'Videos'
form_class = VideoForm
template_name = 'app_video/upload_to_ibm_auto.html'
success_url = reverse_lazy('video_upload_local')
def form_valid(self, form):
# create connection to IBM
cos_client = ibm_boto3.client(service_name='s3',
ibm_api_key_id=settings.IBM_API_KEY_ID,
ibm_service_instance_id=settings.IAM_SERVICE_ID,
ibm_auth_endpoint=settings.IBM_AUTH_ENDPOINT,
config=Config(signature_version='oauth'),
endpoint_url=settings.ENDPOINT)
# assign variables for upload to IBM
upload_name = str(form.cleaned_data['videofilename'])
local_file_name = 'C:/zjunk/' + str(form.cleaned_data['videofile'])
userid = str(self.request.user.id)
uploadtime=str(datetime.datetime.now())
key = userid + '-' + uploadtime + '-' + upload_name
#key='test'+form.cleaned_data['videofilename']
#local_file_name=form.cleaned_data['videofile']
#Bucket=str('cloud-object-storage-3u-cos-standard-77w')
bucket = settings.IBM_STORAGE_BUCKET_NAME
print(bucket)
try:
cos_client.upload_file(Filename=local_file_name, Bucket=bucket, Key=key)
except Exception as e:
print(Exception, e)
else:
print('File Uploaded to IBM')
return super(upload_to_ibm_auto, self).form_valid(form)
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/app_video_upload_to_ibm_auto/
Django Version: 3.2.6
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'drf_spectacular',
'storages',
'app_crm',
'app_video',
'app_library']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Users\Kord\source\repos\storyline\dev\01\PythonDjangoAppLMSUS2021-08-23-SL-1\app_video\views.py", line 163, in form_valid
return super(upload_to_ibm_auto, self).form_valid(form)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
self.object = form.save()
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\forms\models.py", line 468, in save
self.instance.save()
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\sql\compiler.py", line 1358, in as_sql
value_rows = [
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\fields\files.py", line 302, in pre_save
file.save(file.name, file.file, save=False)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\db\models\fields\files.py", line 89, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\core\files\storage.py", line 53, in save
name = self.get_available_name(name, max_length=max_length)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\storages\backends\s3boto3.py", line 585, in get_available_name
return super().get_available_name(name, max_length)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\django\core\files\storage.py", line 87, in get_available_name
while self.exists(name) or (max_length and len(name) > max_length):
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\storages\backends\s3boto3.py", line 457, in exists
self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\client.py", line 386, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\client.py", line 677, in _make_api_call
request_dict = self._convert_to_request_dict(
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\client.py", line 723, in _convert_to_request_dict
api_params = self._emit_api_params(
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\client.py", line 752, in _emit_api_params
self.meta.events.emit(
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\hooks.py", line 357, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\hooks.py", line 211, in _emit
response = handler(**kwargs)
File "C:\Users\Kord\source\repos\storyline\dev\01\venv2\lib\site-packages\botocore\handlers.py", line 235, in validate_bucket_name
if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket):
Exception Type: TypeError at /app_video_upload_to_ibm_auto/
Exception Value: expected string or bytes-like object
Thanks again.

How to filter Serializers in DjangoRestFramework based on user id?

I'm new to django,
I can't seem to find how to return an api based on the user who requested it and created the Transaction object, can you please guide me through? I have read this, but I can't find a clear guide in the docs to update the Serializer straightaway.
In laravel, I can do:
Transaction::where('user_id', Auth::user()->id)->get();
This is my serializer:
class TransactionSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=True)
tags = TagShortSerializer(read_only=True, many=True)
def get_fields(self, *args, **kwargs):
# Override this method so that the list of DatabaseUsers presented in the browseable API
# is restricted to the DatabaseUsers owned by the current user.
fields = super(TransactionSerializer, self).get_fields(*args, **kwargs)
view = self.context["view"]
user = view.request.user
return Transaction.objects.filter(user=user)
class Meta:
model = Transaction
fields = ["user", "title", "amount", "category", "tags"]
My viewset:
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated, IsOwner]
Currently it returns:
Complete traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/transactions/
Django Version: 3.2.5
Python Version: 3.9.5
Installed Applications:
['djmoney',
'rest_framework',
'finance.apps.FinanceConfig',
'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 "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\mixins.py", line 43, in list
return self.get_paginated_response(serializer.data)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 745, in data
ret = super().data
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 500, in to_representation
for field in fields:
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 361, in _readable_fields
for field in self.fields.values():
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 349, in fields
for key, value in self.get_fields().items():
Exception Type: AttributeError at /transactions/
Exception Value: 'QuerySet' object has no attribute 'items'
That is not the correct usage for get_fields. That method returns the list of fields to be used when instantiating the serializer.
What you want is to override get_queryset on your viewset:
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated, IsOwner]
def get_queryset(self):
if self.request.user.is_authenticated:
return self.queryset.filter(user=self.request.user)
return Transaction.objects.none()

Swagger-UI generated python server not starting due to 'no module named' error

I'm working with an OpenAPI 3.0.1 yaml and it's unable to get the API webserver started due to the below error. I tried almost everything that is under my knowledge but I'm very new at OpenAPI and the documentation was followed as it is. Any thoughts on what could be wrong here?
This is the error on loading up the server:
Failed to add operation for GET /v2/catalog
Traceback (most recent call last):
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apis\abstract.py", line 209, in add_paths
self.add_operation(path, method)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apis\abstract.py", line 162, in add_operation
operation = make_operation(
File "C:\Programs\Python\Python38\lib\site-packages\connexion\operations\__init__.py", line 8, in make_operation
return spec.operation_cls.from_spec(spec, *args, **kwargs)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\operations\openapi.py", line 128, in from_spec
return cls(
File "C:\Programs\Python\Python38\lib\site-packages\connexion\operations\openapi.py", line 75, in __init__
super(OpenAPIOperation, self).__init__(
File "C:\Programs\Python\Python38\lib\site-packages\connexion\operations\abstract.py", line 96, in __init__
self._resolution = resolver.resolve(self)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\resolver.py", line 40, in resolve
return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\resolver.py", line 64, in resolve_function_from_operation_id
raise ResolverError(msg, sys.exc_info())
connexion.exceptions.ResolverError: <ResolverError: Cannot resolve operationId "catalog.get"! Import error was "No module named 'catalog'">
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Programs\Python\Python38\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "D:\API\swagger_server\__main__.py", line 25, in <module>
main()
File "D:\API\swagger_server\__main__.py", line 18, in main
app.add_api('D:\API\swagger_server\swagger\swagger.yaml', arguments={'title': 'GPI API Broker'}, pythonic_params=True)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apps\flask_app.py", line 57, in add_api
api = super(FlaskApp, self).add_api(specification, **kwargs)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apps\abstract.py", line 141, in add_api
api = self.api_cls(specification,
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apis\abstract.py", line 111, in __init__
self.add_paths()
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apis\abstract.py", line 216, in add_paths
self._handle_add_operation_error(path, method, err.exc_info)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\apis\abstract.py", line 231, in _handle_add_operation_error
raise value.with_traceback(traceback)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\resolver.py", line 61, in resolve_function_from_operation_id
return self.function_resolver(operation_id)
File "C:\Programs\Python\Python38\lib\site-packages\connexion\utils.py", line 110, in get_function_from_name
module = importlib.import_module(module_name)
File "C:\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'catalog'
The startup command is basically: python -m swagger_server
Finally, this is part of my YAML where the operationId is mentioned:
openapi: 3.0.1
info:
title: Open Service Broker API
description: The Open Service Broker API defines an HTTP(S) interface between Platforms
and Service Brokers.
contact:
name: Open Service Broker API
url: https://www.openservicebrokerapi.org/
email: open-service-broker-api#googlegroups.com
license:
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
version: master - might contain changes that are not yet released
externalDocs:
description: The offical Open Service Broker API specification
url: https://github.com/openservicebrokerapi/servicebroker/
servers:
- url: http://localhost:80/
- url: https://localhost:80/
security:
- basicAuth: []
paths:
/v2/catalog:
get:
tags:
- Catalog
summary: get the catalog of services that the service broker offers
operationId: 'catalog.get'
parameters:
- name: X-Broker-API-Version
in: header
...
Thank you all in advance!
The operationId must be relative to where your app is running.
swagger_server
|-- app.py
|-- __init__.py
|-- OpenAPI
| |-- openapi.yml
|-- models
| |-- catalog.py
Given the above folder structure, you start the app in the directory swagger_server. Consequently, the path of app.py is in your sys.path. Relative to this path you need to specify the operationId in your openapi.yml:
paths:
/v2/catalog:
get:
tags:
- Catalog
summary: get the catalog of services that the service broker offers
operationId: 'models.catalog.get'
The file catalog.py must contain a function def get(name). Here you can define your service/handler for the endpoint. It must include the parameter name because you have specified the parameter in your YAML file.

How do I get $near to work in Flask-mongoalchemy

I have been trying to work on fetching events from my mongoDB database that are close to the current user's location
I have tried to reformat my Model scheme to contain [type: "Point"] and even arranged my longitude and latitude into a list.
I also tried adding "2dsphere" indexes using meta to my Model based on what I saw in mongo-alchemy documentation.
My Model
class Event(db.Document):
meta = {
'indexes': [
("*location.coordinates", "2dsphere")
]
}
user_id = db.StringField()
uuid = db.StringField()
name = db.StringField()
address = db.StringField()
start_time = db.DateTimeField(required=True, default=datetime.datetime.now())
end_time = db.DateTimeField(required=True, default=datetime.datetime.now())
location = db.DictField(db.AnythingField())
This is now my main query code
def get(self):
latitude = float(request.args.get('lat'))
longitude = float(request.args.get('long'))
print(longitude);
print(latitude);
event = Event.query.filter({"location" :
{ "$near" :
{
"$geometry" : {
"type" : "Point",
"coordinates" : [longitude, latitude] },
"$maxDistance" : 4000
}
}
}).first()
print(event);
[2019-01-15 23:20:59,797] ERROR in app: Exception on /v1/event [GET]
Traceback (most recent call last):
File "/home/creative_joe/.local/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/creative_joe/.local/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/creative_joe/.local/lib/python3.5/site-packages/flask_restplus/api.py", line 325, in wrapper
resp = resource(*args, **kwargs)
File "/home/creative_joe/.local/lib/python3.5/site-packages/flask/views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "/home/creative_joe/.local/lib/python3.5/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "/media/creative_joe/3004586c-9a2d-4cb0-8a5f-d41fe99afc05/home/creative_joe/MonkeyMusic.server/app/views/main.py", line 323, in get
"$maxDistance" : 4000
File "/home/creative_joe/.local/lib/python3.5/site-packages/mongoalchemy/query.py", line 139, in first
for doc in iter(self):
File "/home/creative_joe/.local/lib/python3.5/site-packages/mongoalchemy/query.py", line 412, in next
return self._next_internal()
File "/home/creative_joe/.local/lib/python3.5/site-packages/mongoalchemy/query.py", line 416, in _next_internal
value = next(self.cursor)
File "/home/creative_joe/.local/lib/python3.5/site-packages/mongoalchemy/py3compat.py", line 41, in next
return it.next()
File "/home/creative_joe/.local/lib/python3.5/site-packages/pymongo/cursor.py", line 1189, in next
if len(self.__data) or self._refresh():
File "/home/creative_joe/.local/lib/python3.5/site-packages/pymongo/cursor.py", line 1104, in _refresh
self.__send_message(q)
File "/home/creative_joe/.local/lib/python3.5/site-packages/pymongo/cursor.py", line 982, in __send_message
helpers._check_command_response(first)
File "/home/creative_joe/.local/lib/python3.5/site-packages/pymongo/helpers.py", line 155, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: error processing query: ns=heroku_c9gg06k0.EventTree: GEONEAR field=location maxdist=4000 isNearSphere=0
Sort: {}
Proj: {}
planner returned error: unable to find index for $geoNear query

Resources