Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
transaction confirmation takes too time using web3.py
I'm developing a website using python 3.6, Django 2.1.1, Solidity and we3.py v4. I want to add the transaction to ropsten testnet but it takes so much time for tansaction to be confirmed. here is the code: amount_in_wei = w3.toWei(questionEtherValue,'ether') nonce=w3.eth.getTransactionCount(w3.toChecksumAddress(questionairAddress))+1 txn_dict = { 'to': contractAddress, 'value': amount_in_wei, 'gas': 2000000, 'gasPrice': w3.toWei('70', 'gwei'), 'nonce': nonce, 'chainId': 3 } signed_txn = w3.eth.account.signTransaction(txn_dict, wallet_private_key) txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) txn_receipt = w3.eth.getTransactionReceipt(txn_hash) count = 0 while tx_receipt is None and (count < 30): time.sleep(10) tx_receipt = w3.eth.getTransactionReceipt(txn_hash) print(tx_receipt) if tx_receipt is None: return {'status': 'failed', 'error': 'timeout'} -
Django Article text can't be highlighted or linked
I'm very new to Python and Django, but am working with a website that uses article models. The problem I have is that the text inside my articles cannot be highlighted. Not only that, but the links can't be clicked. My process has been to include an srcUrl under the articles model. I make every article that I write into a HTML document and upload it to a separate directory than my main one. In Django admin I link to that document. When I go to just the HTML file, the links work. However, when I view the article in my website, it doesn't work: HTML File | What it looks like on my site I'm wondering if this is the best way to do things. I'm worried that, since the content doesn't show up on inspector, that the keywords in my article don't affect my website. Here is what my models.py looks like: class Article(models.Model): title = models.CharField(max_length=200) abstract = models.TextField() imgUrl = models.CharField(max_length=200) srcUrl = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_on = models.DateTimeField( default=timezone.now) And this is where the content of my articles go in my HTML document: <p class="embed-responsive-item">{{article_content | safe}}</p> Does anyone know how I can … -
Render json object from Django context in Django template as Ajax DataTable
I am looking for a reusable and straightforward solution to render a valid JSON object as an HTML table using Django. The flow is as follows: Views.py from utils load get_data_frame class MyView(TemplateView): template_name = "my_template.html" df = get_data_frame() column_data = [{"field": val, "title": val} for val in df.columns.values] json_object = df.to_json(orient='records') context['json_data'] = json_object context['columns'] = column_data my_template.html <script> var my_data = {{ json_data|safe }}; var column_data = {{ columns|safe }}; $( function() { $( "#my-cool-table" ).dataTable( { "columnDefs": [{ "defaultContent": "-", "targets": "_all" }], "data": my_data, "columns": column_data, }); }); </script> {% if json_data %} <table id="my-cool-table"> <thead> </thead> <tbody> </tbody> </table> {% else %} However, when I render this template the columns show up without issue but the data of the table only renders the default values "-" specified in defaultContent. Am I missing an argument for dataTables? Or is the <script> tag in the wrong location? When I print the variable my_data in the Firefox console it comes up in the format: Array(17) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ] -
open pdf without text with python
I want open a PDF for a Django views but my PDF has not a text and python returns me a blank PDF. On each page, this is a scan of a page : link from django.http import HttpResponse def views_pdf(request, path): with open(path) as pdf: response = HttpResponse(pdf.read(),content_type='application/pdf') response['Content-Disposition'] = 'inline;elec' return response Exception Type: UnicodeDecodeError Exception Value: 'charmap' codec can't decode byte 0x9d in position 373: character maps to < undefined > Unicode error hint The string that could not be encoded/decoded was: � ��`���� How to say at Python that is not a text but a picture ? -
How to cache external meta db table in django?
I am trying to cache external db inside my django program. Here is the sample code I have: class Summary(models.Model): summary_id = models.IntegerField(primary_key=True) name = models.CharField(max=_length=20) class Meta: managed = False db_table = "summary_table_from_specified_db" Basically, I am trying to import a csv file and current logic of my app keeps hitting db as I am trying to use the information to check validity for each row. Talking to db again and again is taking too long. One solution I could think of would be to make another class and import the data over there first time we connect and use that new class from there onwards. Any help would be highly appreciated. -
Associate a specific objects from the dependent model for each row of another model in Django
I have these models: class Project(models.Model): name = models.CharField(max_length=100) class Milestone(models.Model): project = models.ForeignKey(Project, related_name='milestones', on_delete=models.CASCADE) description = models.CharField(max_length=100) completed = models.BooleanField(default=False) ...and example data: {name: 'SpaceY', milestones: [{id:1, project: 1, description: '1st milestone description',completed: False}, {id: 2, project: 1, description: '2nd description',completed: False}]}, {name: 'ProjectX', milestones: [{id:3, project: 2, description: 'ProjectX 1st Desc',completed: True}, {id: 4, project: 2, description: 'one more description',completed: False}]} ... and I need output like this: {name: 'SpaceY', milestone: {id:1, project: 1, description: '1st milestone description', completed: False}}, {name: 'ProjectX', milestone: {id: 4, project: 2, description: 'one more description', completed: False}} i.e. I want only one not completed milestone with the smallest id for every Project. And no Project if all milestones were completed. I've tried to use prefetch_related and other things but the best I got was many duplicated Projects. May it be solved with Django ORM or I need dive into raw sql? -
Django Profile Update on existing profile
I have the following signal for creating a profile when a new user registers and then sends an email to the admin informing them of the new user @receiver(post_save, sender=User) def create_user_profile(sender, **kwargs): '''Create a profile for a new user''' if kwargs['created']: Profile.objects.create(user=kwargs['instance']) @receiver(post_save, sender=User) def notify_admin(sender, instance, created, **kwargs): '''Notify the administrator that a new user has been added.''' if created: subject = 'New Registration created' message = 'A new candidate %s has registered with the site' % instance.email from_addr = 'no-reply@example.com' recipient_list = ('admin@example.com',) send_mail(subject, message, from_addr, recipient_list) I am looking to also notify the admin when a profile is updated but am struggling to come up with a solution. Any help would be appreciated. -
subclassing django-registration ActivationView is always producing "The activation key you provided is invalid."?
I'm trying to use django-registration as the core process for registration at a site, but I'm also trying to set the email to the username and not actually activate the user until admin have done something. Subclassed the views as follows: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django_registration.backends.activation.views import ActivationView, RegistrationView # Create your views here. from my_registration.forms import NoUsernameRegistrationForm class MyActivationView(ActivationView): def activate(self, *args, **kwargs): username = self.validate_key(kwargs.get('activation_key')) user = self.get_user(username) user.is_active = False user.save() return user class NoUsernameRegistrationView(RegistrationView): form_class = NoUsernameRegistrationForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django_registration.forms import RegistrationForm attrs_dict = {'class': 'required'} class NoUsernameRegistrationForm(RegistrationForm): """ Form for registering a new user account. Requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user data is delegated to the active registration backend. """ username = forms.CharField( widget=forms.EmailInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email address")) password1 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password")) password2 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (again)")) email = forms.EmailField( widget=forms.HiddenInput(), required = False) def __init__(self, *args, **kwargs): super(NoUsernameRegistrationForm, self).__init__(*args, … -
How can I show my last 3 posts with Django Python
I try to show my last 3 posts with Django but it doesn't work. There is my code. I have no error or anything when I load the page. And please be kind it's the first time I use Python and Django =) models.py from django.db import models from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) category = models.ForeignKey('Category') def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views from django.shortcuts import render from django.utils import timezone from .models import Category, Post def category_list(request): categories = Category.objects.all() return render (request, 'blog/post_list.html', {'categories': categories}) def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def latest_posts(request): latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3] return render(request, 'blog/post_list.html', {'latest': latest}) My urls from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), ] template html (post_list.html) {% for latest in latests %} <article class="lastnews"> <h4>{{ latest.title }}</h4> <h5 class="lastestcategory">{{ latest.category }}</h5> <p class="bodysmall">{{ latest.text|truncatewords:10 }}</p> <div> <p class="date">{{ latest.published_date }}</p> <p class="showmore"><a href="">Show more</a></p> </div> </article> {% endfor %} Thanks for your help =) -
Django Post or None
I am trying to query with multiple filters or none technician = request.POST.get('technician') ## in the previous screen the user may not have informed the parameter, it should not be required uniorg = request.POST.get('uniorg') ## in the previous screen the user may not have informed the parameter, it should not be required calls = Call.objects.filter( technician=technician, uniorg=uniorg, ...) I tried: technician = request.POST.get('technician', '') and technician = request.POST.get('technician' or None) Not all parameters are required. Someone can help me? -
Django complains that query must be used in subquery, when it is being used in a subquery
I have the following custom QuerySet method for a model called Program: def with_volunteer_stats(self): from programs.models import Session volunteers_needed = ExpressionWrapper( F('num_student_seats') / F('student_volunteer_ratio'), output_field=models.IntegerField()) sessions = ( Session.objects.filter(program_id=OuterRef('pk')) .annotate(num_volunteers=Count('volunteer_attendances__volunteer', distinct=True)) .order_by('num_volunteers') ) qs = self.annotate( volunteers_needed=volunteers_needed, least_volunteers=Subquery(sessions.values('num_volunteers')[0]) ).annotate( remaining_volunteers_needed=(F('volunteers_needed') - F('num_volunteers')) ) return qs When running this, I get the exception: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. The traceback shows the exception occurring on the evaluation of the line using Subquery. This is very close to the example in the Django documentation on how to use Subquery. Any ideas what I'm doing wrong? -
Can I use get_FOO_display() in a Model's save method?
I am using self.get_category_display() in two separate model functions: class Document(models.Model): category = models.IntegerField(choices=choices.DOC_CATEGORIES, null=True) shipment = models.ForeignKey(Shipment, null=True) file = models.FileField() def __str__(self): return "{}.{}.pdf".format(self.shipment.__str__(), self.get_category_display().upper()) def save(self, *args, **kwargs): count = Document.objects.filter(shipment__purchase__contract=self.shipment.purchase.contract).count() + 1 new_name = "{}-{:03d}.{}.pdf".format(self.shipment.purchase.contract.number, count, self.get_category_display().upper()) self.file.name = new_name super(Document, self).save(*args, **kwargs) This works as expected in the .__str__() function, but not in the .save() function. For .save(), it simply returns the choice's integer instead of the display string. Is there a way to get the choice's string from .save()? -
How do I add a dynamic base template in django?
Suppose I have a base.html template. In the base.html template contains the menu bar, the fixed footer and the content block. Exemple: base.html <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand mr-0 mr-md-2" href="/"> <img src="{{ url of an image added in the database that can be changed by the user }}" height="60" class="d-inline-block" alt="site">Site</a> <button class="btn btn-link bd-search-docs-toggle d-md-none p-0 ml-3" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Diário Oficial do PL</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Site Oficial do PL</a> </li> <li> <a class="nav-link" href="#">Links Úteis</a> </li> </ul> </div> <div class="container" style="min-height: calc(100vh - 230px);"> {% block content %} <!-- Blocl content --> {% endblock %} </div> {% block footer %} {% endblock %} home.html {% extends 'base/base.html' %} {% load static %} {% block conteudo %} <p>Content bla bla bla bla bla </p> {% endblock %} models.py class Orgao(models.Model): name = models.CharField(max_length=80) logo = models.ImageField() How would a view that would take this image in the database and show in the base.html that is extended to all the pages of the system? -
undefined name in function 'redirect'
any advice on whats the problem? Im learning from a Django v1 tutorial but ive had a look at the documentation but cannot figure out why it does not work. imports: from django.shortcuts import render from accounts.forms import RegistrationForm from django.contrib.auth.forms import UserChangeForm function: def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST instance=request.user) if form.is_valid(): form.save() return redirect('/account/profile') else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) thanks -
Apply pagination to Raw query to prevent ALL records being loaded
I have the following class based view that works as expected and paginates the results as required with parameters http://127.0.0.1:8000/api/collection/fromdetroit?page=1 >> ?page=2 etc class ListReleasesCollectionView(APIView): def get(self, request, format=None, *args, **kwargs): try: releases = ReleasesAll.objects.raw('SELECT releases.*, \'\' as num FROM releases_all releases INNER JOIN release_artists ra ON ra.release_id=releases.id LEFT JOIN genre_artists ON genre_artists.artist=ra.artists LEFT JOIN genre_labels ON genre_labels.label=releases.label_no_country WHERE genre_artists.genre=%s OR genre_labels.genre=%s GROUP by releases.id ORDER BY releases.date DESC',(kwargs['collection'],kwargs['collection'])) paginator = PageNumberPagination() result_page = paginator.paginate_queryset(releases, request) serializer = ReleasesSerializer(result_page, many=True, context={'request': request}) response = Response({'results':{'image_url':'', 'page_header':'','releases': serializer.data}}, status=status.HTTP_200_OK) return response except ReleasesAll.DoesNotExist: return Response( data = { "message": "{} does not exist".format(kwargs["collection"]) }, status=status.HTTP_404_NOT_FOUND ) However, it runs incredibly slowly because it has to download ALL results first and then paginate after. Here are the results from Django Toolbar. I would like to only download 60 results at a time as there are thousands of results returned above. Pagination settings in settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } -
Conditional field rendering django admin
I am new to Django. I would like to show some fields in the Django Admin only if a specific value has been selected on a dropdown. For instance, I have a question model. I would like to let the user select the type of question. If it is a multiple choice question, I would like to show fields to let the user fill the possible answers. I have found this link but it seems that it is not done for the Django Admin. How should I proceed to achieve what I need ? -
Django form : Doesn't display any form errors
I'm getting an issue with my Django form validation. I would like to display form errors and make all fields required. I don't know why my fields can accept blank while blank is not defined in my model file. This is my model : class Customer(models.Model): email = models.CharField(max_length=150, verbose_name=_('e-mail'), null=False) first_name = models.CharField(max_length=70, verbose_name=_('first name'), null=False) last_name = models.CharField(max_length=70, verbose_name=_('last name'), null=False) country = models.ForeignKey(Country, verbose_name=_('country')) institution = models.CharField(max_length=255, verbose_name=_('institution'), null=True) creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False) modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False) class Meta: verbose_name = _('customer') verbose_name_plural = _('customer') def __str__(self): return f"{self.email}" This is my form : class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) self.fields['country'].empty_label = _('Select a country') self.fields['country'].queryset = self.fields['country'].queryset.order_by( 'name') for key in self.fields: self.fields[key].required = True class Meta: model = Customer fields = ['email', 'first_name', 'last_name', 'country', 'institution'] widgets = { 'email': forms.TextInput(attrs={'placeholder': _('name@example.com')}), 'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}), 'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}), 'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}), } You can find here my view with Django CBV : class HomeView(CreateView): """ Render the home page """ template_name = 'freepub/index.html' form_class = CustomerForm def get_context_data(self, **kwargs): kwargs['document_list'] = Document.objects.all().order_by('publication__category__name') return super(HomeView, self).get_context_data(**kwargs) def post(self, request, *args, **kwargs): if … -
Unity WebRequest Post and django REST framework
I am setting up simple communication between the django REST server and unity. While the get method works perfectly, I encountered a weird issue. I hope you can lead me to the answer. UNITY: public class UserStats : ClassesManager { public int userID; public int victory; public int defeat; } public class ServerCommunication : MonoBehaviour { UserStats stats; private void Start() { Debug.Log("START"); StartCoroutine(ServerCommunicationProcess()); } private IEnumerator ServerCommunicationProcess() { // This is just an example, // in my code stats are created from json coming from server stats = UserStats (); UnityWebRequest req = UnityWebRequest (serverURL, JsonUtility.ToJson(stats)); yield return req.Send (); } On a server side I have print (request.data) so I can see what actually is coming. Now, when I do post request in the python shell: post = requests.post (url, headers=headers, data={'userID': 621, 'victory': 10, 'defeat': 0}) Server console outputs: <QueryDict: {'defeat': ['0'], 'userID': ['621'], 'victory': ['10']}> But when I run Unity code, console outputs: <QueryDict: {"{'userID':621,'victory':23,'defeat':0}": ['']}> What is happening here? Where should I fix it? I fill it has something to do with Unity rather than with Django, but still. It is frustrating. -
What do you recommend if I want to list all [PostgreSQL] database tables in a [Django] web-application and [SQL] query them?
I am building a web application with the Django framework that uses a PostgreSQL database filled with shapefile data. On my website, I want to do two things with that data. (1)I want to list all the tables on my website and (2) I want to run SQL queries on the data from those tables. (1)I want to list all the tables on my website I want users to be able to save those tables to their user accounts for future use as a "project" When users click on the table in the list I want it to show a preview of the data in that table. (2) I want to run SQL queries on the data from those tables I want users to be able to query data from tables that they saved as their "project" using SQL, on a different web page/web app. I want to be able to run queries with PostGIS. I understand Django has legacy database support, using the inspectdb command. Will this work if I am continually updating my database with new tables? I suspect it won't be very practical. Do you have any suggestions for me to accomplish this without having to create … -
Pagination with Raw SQL in Django Rest Framework?
I have this in settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 60 } Page size/pagination is obeyed in ORM queries but not in Raw SQL queries. How can I use pagination in raw? Example of raw query class in views.py: class ListReleasesCollectionView(APIView): def get(self, request, format=None, *args, **kwargs): try: a_release = ReleasesAll.objects.raw('SELECT releases.*, \'\' as num FROM releases_all releases INNER JOIN release_artists ra ON ra.release_id=releases.id LEFT JOIN genre_artists ON genre_artists.artist=ra.artists LEFT JOIN genre_labels ON genre_labels.label=releases.label_no_country WHERE genre_artists.genre=%s OR genre_labels.genre=%s GROUP by releases.id ORDER BY releases.date DESC',(kwargs['collection'],kwargs['collection'])) return Response(ReleasesSerializer(a_release, many=True).data) except ReleasesAll.DoesNotExist: return Response( data = { "message": "{} does not exist".format(kwargs["collection"]) }, status=status.HTTP_404_NOT_FOUND -
How to override username max_length in Django?
I'm using Django 1.9, where usernames have a 30 character limit. In order to overcome this, I created a custom user model as such: class User(AbstractUser): pass # Override username max_length to allow long usernames. User._meta.get_field('username').max_length = 255 User._meta.get_field('username').help_text = _( 'Required. 255 characters or fewer. Letters, digits and @/./+/-/_ only.') In the shell I can create users with names longer than 30 characters, but in the admin I cannot add users with long usernames or assign long usernames to existing users. I get: Ensure this value has at most 30 characters (it has 43). I noticed that Django Admin's UserCreateForm and UserChangeForm have Django's default User model explicitly set in their Meta options, so I used custom forms like this: from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm User = get_user_model() class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm Still it didn't work. So I added a breakpoint to the CustomUserChangeForm's init, after calling super, and I got: ipdb> self <UserForm bound=True, valid=False, fields=(username;password;first_name;last_name;email;is_active;is_staff;is_superuser;groups;user_permissions)> ipdb> self.fields['username'].max_length 255 ipdb> self.fields['username'].validators[0].limit_value 255 ipdb> self.fields['username'].clean('a_username_with_more_than_thirty_characters') u'a_username_with_more_than_thirty_characters' ipdb> self.errors {'username': [u'Ensure this value has … -
Django: Attach ICS file with Meeting Response
I am trying to attach ICS files to emails sent via Django that when received includes the option to Accept, Tentative, Decline, Propose New Time in Outlook. meeting-response Currently, I am able to attach the ICS file to the email however it is not providing the options I stated above. ics attachment Below is how I am handling the ICS file, attaching it, and sending the email: #OPEN 'invite.ics' write generated ICS to file f = open(os.path.dirname(os.path.realpath(__file__)) + '/attachments/invite.ics', 'w') f.write(ical) f.close() #COMPOSE EMAIL msg = EmailMultiAlternatives(subject, description, fro, attendees) #Attach ICS file msg.attach_file(os.path.dirname(os.path.realpath(__file__)) + '/attachments/invite.ics') #for HTML email template msg.attach_alternative(html_message, "text/html") msg.send() -
How do I configure apache 2.4 to run django and flask app simultaneously?
We are trying to run one django web app and one flask web app on apache 2.4 at the same time. We succeeded in getting django web app up and running. But we are struggling to add the flask instance. httpd.conf: LoadModule wsgi_module "C:/Program Files/Python36/lib/site-packages/mod_wsgi-4.6.4-py3.6-win-amd64.egg/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "C:/projects/production/title-project/title/wsgi.py" WSGIPythonHome "C:/Program Files/Python36" WSGIPythonPath "C:/projects/production/title-project" Alias /static/ C:/projects/production/title-project/static/ <Directory C:/projects/production/title-project/static> Require all granted </Directory> <Directory "C:/projects/production/title-project"> <Files wsgi.py> Require all granted </Files> </Directory> This, we put without any virtual host tag. Now, if we try putting a virtual host tag after the above snippet, <VirtualHost *:8080> ServerName localhost DocumentRoot C:/projects/production <Directory "C:/projects/production/"> Require all granted </Directory> LoadModule wsgi_module "C:/Program Files/Python36/lib/site-packages/mod_wsgi-4.6.4-py3.6-win-amd64.egg/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias /flaskapp C:/projects/production/title-reporting/reporting.wsgi <Directory C:/projects/production/title-reporting> Require all granted </Directory> </VirtualHost> We are not able to connect to the flask app at all. We are aware that there is something wrong above. But we do not have much experience with Apache and we'd love some help. Thanks. -
Detect gunicorn worker restart
We have a django application served through gunicorn sync workers. There's a tornado server run in a thread from the django application itself(Let's not argue about architecture, it's legacy code) and is tightly coupled with worker. It binds itself to a free port stored in a db. Now every time a worker restarts, I would need to start the tornado too, but since the port has been used it won't start. I would need to somehow detect that worker went down and would need to store the state of port to available. However any I am now able to detect that anyhow. signal.signal(signal.SIGTERM, stop_handler) signal.signal(signal.SIGINT, stop_handler) Above are only detected when I manually kill the worker but not when gunicorn restarts the worker itself. How can I detect the same? -
Terminate VIEWS.PY function Execution if exceed certain time - DJANGO
I need to terminate function if it exceed certain time, by google it I found a solution but face another problem now. I am doing some thing like this. def index(Request): p = multiprocessing.Process(target=foo, name="Foo", args=(5,)) p.start() # Wait 10 seconds for foo time.sleep(10) # Terminate foo p.terminate() # Cleanup p.join() return HttpResponse("exit") //run foo for 25 second def foo(n): for i in range(5 * n): times = strftime("%H:%M:%S", gmtime()) print (times) time.sleep(1) above solve my problem where it terminate a process after 10 second but IN CASE IF FOO FUNCTION COMPLETE ITS TASK IN 5 SECOND BUT STILL IT TAKE 10 SECOND TO COMPLETE MAIN THREAD because of time.sleep(10) So I wanted to end thread if foo complete its execution or if it take more then certain amount of time so also terminate it. Thank You