Graphene Returning NoneType Error on Subscription - django

I'm trying to setup subscription on graphene-django and channels using channels_graphql_ws.
I'm getting the following error when trying to run my subscription query:
An error occurred while resolving field Subscription.onNewComment
Traceback (most recent call last):
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executor.py", line 450, in resolve_or_error
return executor.execute(resolve_fn, source, info, **args)
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executors/sync.py", line 16, in execute
return fn(*args, **kwargs)
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/channels_graphql_ws/subscription.py", line 371, in _subscribe
register_subscription = root.register_subscription
AttributeError: 'NoneType' object has no attribute 'register_subscription'
Here is what I have in my setup:
# /subscription.py/
class OnNewComment(channels_graphql_ws.Subscription):
comment = Field(types.UserCommentNode)
class Arguments:
content_type = String(required=False)
def subscribe(root, info, content_type):
return [content_type] if content_type is not None else None
def publish(self, info, content_type=None):
new_comment_content_type = self["content_type"]
new_comment = self["comment"]
return OnNewComment(
content_type=content_type, comment=new_comment
)
#classmethod
def new_comment(cls, content_type, comment):
cls.broadcast(
# group=content_type,
payload={"comment": comment},
)
I'm not sure if this is a bug or if I'm missing something.

I found out that graphne's graphiql template doesn't come with websocket support and I had to modify my graphene/graphiql.html file to incorporate websocket to get it to work.

Related

Django - Unit test an object has been deleted - how to use assertRaise / DoesNotExist exception

I would lioke some help to unit test a function that deletes an object in a Django app
The problem
I display a list of values, it includes a bin icon to delete one value, and my view seems to work fine (at least according to the test I made).
How can I unit test it? I'm not able to find out the right way to do yet.
I searched the web and found the DoesNotExist exception, but I'm afraid I'm not able to use it, as I got a matching query does not exist error.
Could you please advise me on how to proceed?
What I tried
Here is my current whole code for the test:
class TestAdmUsers(TestCase):
def setUp(self):
self.company = create_dummy_company("Société de test")
self.usr11 = create_dummy_user(self.company, "user11")
self.usr13 = create_dummy_user(self.company, "user13")
self.usr14 = create_dummy_user(self.company, "user14")
self.client.force_login(self.user_staff.user)
def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))
The test log is the following:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 1.763s
FAILED (errors=1)
Destroying test database for alias 'default'...
I made other tests like this one:
def test_delete_user(self):
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(response, self.usr13.user.username)
that leads to this:
======================================================================
FAIL: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user
self.assertNotContains(response, self.usr13.user.username)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\test\testcases.py", line 465, in assertNotContains
self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr)
AssertionError: 1 != 0 : Response should not contain 'user13'
----------------------------------------------------------------------
Or this one:
def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
users = UserComp.get_users_in_comp(self.company.comp_slug)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(users, self.usr13)
with the following result:
======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\base.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
And this latest one that uses a class method:
def test_delete_user(self):
current_username = self.usr13.user.username
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(UserComp.get_users_in_comp(self.company.comp_slug), self.usr13)
but the result is still an error:
`======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\base.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
Related application code
Here is the code for the view:
def adm_delete_user(request, comp_slug, usr_id):
del_usr = User.objects.get(pk=usr_id)
msg = "Utilisateur {0} {1} supprimé.".format(del_usr.last_name, del_usr.first_name)
User.objects.get(pk=usr_id).delete()
messages.success(request, msg)
return redirect("polls:adm_users", comp_slug=comp_slug)
And the model:
class UserComp(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur")
company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société")
phone_regex = RegexValidator(regex=r'^0[0-9]([ .-]?[0-9]{2}){4}$', message=("Format de numéro de téléphone invalide"))
phone_num = models.CharField("numéro de téléphone", validators=[phone_regex], max_length=14, null=True, blank=True)
is_admin = models.BooleanField("administrateur", default=False)
def __str__(self):
return '%s %s' % (self.user.last_name, self.user.first_name)
class Meta:
verbose_name = "Liens Utilisateurs / Sociétés"
verbose_name_plural = "Liens Utilisateurs / Sociétés"
#classmethod
def create_usercomp(cls, user, company, phone_num='', is_admin=False):
""" Create a new UserComp """
usr_comp = UserComp(user=user, company=company, phone_num=phone_num, is_admin=is_admin)
usr_comp.save()
return usr_comp
#classmethod
def get_users_in_comp(cls, comp_slug):
user_list = cls.objects.filter(company__comp_slug=comp_slug)
return user_list
Complementary search results
Finally, I found some posts here that oriented my tests, but I wasn't able to find the solution:
The most important to me leads me to assertRaise() test
Unfortunately, the one that asked how to use this exception has been closed, and referred to the previous one, but actually there is no information on how to proceed
This other one asking about the exception, and this one related to the error message did not give me any additional information.
assertRaises takes a callable as its (optional) second argument.
Since .get(...) is not a callable, you should use the context manager form instead:
with self.assertRaises(UserComp.DoesNotExist):
UserComp.objects.get(id=test_usercomp_id)

Django Model QuerySet: RuntimeError generator raised StopIteration

I've recently updated my Django to version 2.2.4 and python to 3.7,
and I encounter this error randomly:
Traceback (most recent call last):
File "/foo/venv/lib/python3.7/site-packages/django/db/models/query.py", line 73, in __iter__
obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
File "/foo/venv/lib/python3.7/site-packages/django/db/models/base.py", line 511, in from_db
for f in cls._meta.concrete_fields
File "/foo/venv/lib/python3.7/site-packages/django/db/models/base.py", line 511, in <listcomp>
for f in cls._meta.concrete_fields
StopIteration
I tried to debug the code to find out what's happening, and it seems the from_db function in django.db.models.base.py is causing this error:
# /foo/venv/lib/python3.7/site-packages/django/db/models/base.py
...
#classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
...
next(values_iter) is raising this error and it seems that Django devs should surround that with try except block to make this work in python 3.7,
but my question is, is there a way to overcome this issue as a temp fix or not?
thanks.
Update#1:
I've found out when exactly this error happens, When I call .values_list('myfield', flat=True) on a QuerySet, the query changes to SELECT myfield from ... and this breaks everything.

Error when loading the word2vec model

I am using the following function to load my word2vec model.
def __init__(self, filename):
print filename
try:
self.model = gensim.models.Word2Vec.load(filename)
except cPickle.UnpicklingError:
load = gensim.models.Word2Vec.load_word2vec_format
self.model = load(filename, binary=True)
However, I am getting the following error when I try to do it.
Traceback (most recent call last):
File "./explore", line 70, in <module>
api_controller.model = Model(sys.argv[1])
File "/home/volka/Documents/projects/word2vec-explorer/explorer.py", line 77, in __init__
self.model = gensim.models.Word2Vec.load(filename)
File "/usr/local/lib/python2.7/dist-packages/gensim/models/word2vec.py", line 1458, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gensim/utils.py", line 256, in load
obj = unpickle(fname)
File "/usr/local/lib/python2.7/dist-packages/gensim/utils.py", line 920, in unpickle
return _pickle.loads(f.read())
AttributeError: 'module' object has no attribute 'call_on_class_only'
The genism version I am using in both the versions are 0.12.3.
Please let me know where I am making it wrong?
This is how I tried to remove call_on_class_only.
model = word2vec.Word2Vec(text, sg=0, negative=5, hs=0)
model.save("test_project")
#load, delete and save
model_1 = word2vec.Word2Vec.load("test_project")
del model_1.call_on_class_only
model.save(model_name_2)
It gives me the following error: AttributeError: call_on_class_only
Please help me.

Flask throwing 'Working outside of request context.'

I am trying to use celery for my app which is made in flask but I get the following error "Working outside of request context". It sounds like I am trying to access a request object before the front end makes a request, but I cannot figure out what is wrong. I appreciate if you can let me know what is the problem.
[2017-04-26 13:33:04,940: INFO/MainProcess] Received task: app.result[139a2679-e9df-49b9-ab42-1f53a09c01fd]
[2017-04-26 13:33:06,168: ERROR/PoolWorker-2] Task app.result[139a2679-e9df-49b9-ab42-1f53a09c01fd] raised unexpected: RuntimeError('Working outside of request context.\n\nThis typically means that you attempted to use functionality that needed\nan active HTTP request. Consult the documentation on testing for\ninformation about how to avoid this problem.',)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/celery/app/trace.py", line 367, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/Pooneh/projects/applications/ray_tracer_app_flask/flask_celery.py", line 14, in __call__
return TaskBase.__call__(self, *args, **kwargs)
File "/Library/Python/2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/Pooneh/projects/applications/ray_tracer_app_flask/app.py", line 33, in final_result
light_position = request.args.get("light_position", "(0, 0, 0)", type=str)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object
return self.__local()
File "/Library/Python/2.7/site-packages/flask/globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
app.py
app = Flask(__name__)
app.config.update(CELERY_BROKER_URL = 'amqp://localhost//',
CELERY_RESULT_BACKEND='amqp://localhost//')
celery = make_celery(app)
#app.route('/')
def my_form():
return render_template("form.html")
#app.route('/result')
def result():
final_result.delay()
return "celery!"
#celery.task(name='app.result')
def final_result():
light_position = request.args.get("light_position", "(0, 0, 0)", type=str)
light_position_coor = re.findall("[-+]?\d*\.\d+|[-+]?\d+", light_position)
x = float(light_position_coor[0])
y = float(light_position_coor[1])
z = float(light_position_coor[2])
encoded = base64.b64encode(open("/Users/payande/projects/applications/app_flask/static/pic.png", "rb").read())
return jsonify(data=encoded)
Celery tasks are run by a background worker asynchronously outside of the HTTP request (which is one of they main benefits of using them), so you cannot access the request object within the task.
You could pass the data to the task as arguments instead:
final_result.delay(request.args.get("light_position"))
#celery.task(name='app.result')
def final_result(light_position):
...
Of course this also means that the return value of the task cannot be used in a HTTP response (since the task can complete after the response has been already sent).

django get_profile error

I want to get my userprofile id in the views i have already included below in settings.py
AUTH_PROFILE_MODULE = 'users.UserProfile'
views code:
def savecontent(request):
try:
logging.debug("=========================== in save content")
logging.debug(dir(request.user))
my_id = request.user.get_profile().id
logging.debug(my_id)
Error is:
2012-07-17 13:00:00,564 ERROR Error while saing content
Traceback (most recent call last):
File "/opt/labs/labs_site/content/views.py", line 21, in savecontent
my_id = request.user.get_profile().id
File "/opt/labs/django/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute 'get_profile'
AttributeError: 'AnonymousUser' object has no attribute 'get_profile'
You must have an authenticated user to retrieve a profile, that's your problem
#login_required
def foo(request):
profile_id = request.user.get_profile().id