Django Tastypie slow POST response

2024/9/25 5:20:57

I'm trying to implement a Tastypie Resource that allows GET & POST operations following a per user-permission policy, the model is pretty simple (similar to the Note model in Tastypie documentation) and the resource itself is also pretty simple, I just have an extra override_urls method to implement search with Haystack.

My main problem now is that although running the project locally seems to be working fine, requests are fast and everything. Once I deployed the project (On Linode, using Nginx, Gunicorn, Runit), I discovered that POST requests are too slow, taking about a 1.1 min to come back with a 201 status. GET requests on the other hand are working well and as expected.

I ran a Python Hotshot profiler on the request and it's showing that the entire POST request is taking 0.127 CPU seconds. I'm not really sure what's happening here.

I should mention that I'm using ApiKeyAuthentication and DjangoAuthorization for my Tastypie resource.

Here's a screenshot from Chrome Inspector for the request: http://d.pr/i/CvCS

It would be great if anyone can direct me into the correct direction to look for an answer for this problem.

Thanks!

Edit:

Some code:

Models & Resource:

class Note(models.Model):timestamp = models.DateTimeField('Timestamp')user = models.ForeignKey(User)page_title = models.CharField("Page Title", max_length=200)url = models.URLField('URL', verify_exists=False)summary = models.TextField("Summary")notes = models.TextField("Notes", null=True, blank=True)def __unicode__(self):return self.page_titledef get_absolute_url(self):return self.urlclass NoteResource(ModelResource):user = fields.ForeignKey(UserResource, 'user')class Meta:queryset = Note.objects.all()resource_name = 'note'list_allowed_methods = ['get', 'post']detail_allowed_methods = ['get']always_return_data = Trueauthentication = ApiKeyAuthentication()authorization = DjangoAuthorization()# authentication = Authentication() #allows all access# authorization = Authorization() #allows all accessordering = ['-timestamp']def override_urls(self):return [url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()),self.wrap_view('get_search'), name="api_get_search"),]def obj_create(self, bundle, request=None, **kwargs):return super(NoteResource, self).obj_create(bundle,request,user=request.user)def apply_authorization_limits(self, request, object_list):return object_list.filter(user=request.user)def get_search(self, request, **kwargs):self.method_check(request, allowed=['get'])self.is_authenticated(request)sqs = SearchQuerySet().models(Note).filter(user=request.user).auto_query(request.GET.get('q', ''))paginator = Paginator(sqs, 100)try:page = paginator.page(int(request.GET.get('page', 1)))except InvalidPage:raise Http404("Sorry, no results on that page.")objects = []for result in page.object_list:bundle = self.build_bundle(obj=result.object, request=request)bundle.data['score'] = result.scorebundle = self.full_dehydrate(bundle)objects.append(bundle)object_list = {'objects': objects,}self.log_throttled_access(request)return self.create_response(request, object_list)

Gunicorn Conf:

bind = "0.0.0.0:1330"
workers = 1

Nginx Conf (included in the main nginx.conf):

server {listen 80;server_name domain.com example.com;access_log  /path/to/home/then/project/access.log;error_log /path/to/home/then/project/error.log;location / {proxy_pass   http://127.0.0.1:1330;}location /static/ {autoindex on;root /path/to/home/then/project/;}
}
Answer

OP: Figured it out. In the main nginx.conf file (/etc/nginx/nginx.conf), turns out I had keepalive_timeout set on 65, which is considered too much. I switched it to 0 and everything worked ok.

Sorry, I spend a couple of minutes with this question, then realized there were more comments and then realized the OP did find a solution :( and did not mark it as answered.

https://en.xdnf.cn/q/71499.html

Related Q&A

Extract a region of a PDF page by coordinates

I am looking for a tool to extract a given rectangular region (by coordinates) of a 1-page PDF file and produce a 1-page PDF file with the specified region:# in.pdf is a 1-page pdf file extract file.pd…

Is it possible to concatenate QuerySets?

After a search of a database I end up with an array of querysets. I wanted to concatenate these queryset somewhat like we can do with list elements. Is this possible or maybe there an altogether better…

Pickling a Python Extension type defined as a C struct having PyObject* members

I am running C++ code via Python and would like to pickle an extension type.So I have a C++ struct (py_db_manager) containing pointers to a database object and a object manager object (both written in …

Generating random ID from list - jinja

I am trying to generate a random ID from a list of contacts (in Python, with jinja2) to display in an HTML template. So I have a list of contacts, and for the moment I display all of them in a few cell…

Unit testing Flask app running under uwsgi

I’m relatively new to python and am looking for a pythonic way to handle this practice. I’ve inherited a fairly trivial Python 2.7 Flask app that runs under uwsgi that I want to add some unit tests t…

fastest way to find the smallest positive real root of quartic polynomial 4 degree in python

[What I want] is to find the only one smallest positive real root of quartic function ax^4 + bx^3 + cx^2 + dx + e [Existing Method] My equation is for collision prediction, the maximum degree is quarti…

Split strings by 2nd space

Input :"The boy is running on the train"Output expected:["The boy", "boy is", "is running", "running on", "on the", "the train"]Wha…

Searching for a random python program generator

Im searching for a program that can generate random but valid python programs, similar to theRandom C program generator. I was trying to do this myself giving random input to the python tokenize.untoke…

Python tk framework

I have python code that generates the following error:objc[36554]: Class TKApplication is implemented in both /Library/Frameworks/Tk.framework/Versions/8.5/Tk and /System/Library/Frameworks/Tk.framewor…

SQLAlchemy relationship on many-to-many association table

I am trying to build a relationship to another many-to-many relationship, the code looks like this: from sqlalchemy import Column, Integer, ForeignKey, Table, ForeignKeyConstraint, create_engine from …