Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have got error when ı add trying to add column in my sqlite database in django
ı have trying to change my database to postgreSQL but but whenever ı have trying to makemigrations ı got an Error which attached on bellow: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such column: Projects_project.abbr The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 21, in <module> main() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 395, in execute django.setup() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin_init_.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\cukad\AppData\Local\Programs\Python\Python311\Lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\Projects\admin.py", line 24, in <module> class ProjectListFilter(admin.SimpleListFilter): … -
Django User Model Optimization
UserModel has many entries on it. The 3 UserModel queries run very slow. How to make needed changes and optimizations to UserModel to make the 3 queries run faster? class UserModel(models.Model): username = CharField(max_length=255) role = JSONField() # format of ['admin', 'operator'] UserModel.objects.filter(username='john').first() UserModel.objects.filter(username__contains='doe').first() UserModel.objects.filter(role__contains='operator').first() -
Django manual reset password handling
Our system based without physical templates. All templates stored in database. Template render with HttpResponse and Template classes. I cant use django built-in GenereicViews. How can i manualy handle forgot password and reset password logic, email sending with a unique link? -
get user group name from a specific text in django
In django, user posts in a simple HTML form. In form, there is a field which called "technician_name". I'm getting the post with "name attribute" and write it to database. I want additional thing: after I take the name attribute, I want to check the group of technician. Simply: I want to check user's group according to specific text. For example: user posted the "John Doe". if request.method == 'POST' action_man = request.POST.get('technician_name') Output: action_man = "John Doe" I need this action_man's user group. The action_man's name same with username, so I can query in django auth. Note: I don't need the logged in user's group. I need action man's group. -
Avoid CSRF_TRUSTED_ORIGINS in Django 4.1
I've a dockerized Django project which I access through NGINX. I just upgraded to Django 4.1 and now it seems that it's mandatory to define a CSRF_TRUSTED_ORIGINS listing, I would like to know if there is a way to allow POST requests from any source. I've tried installing https://github.com/ottoyiu/django-cors-headers and setting CORS_ALLOW_ALL_ORIGINS to TRUE but it didn't work :/ Also I tried setting CSRF_TRUSTED_ORIGINS = ['*'] as I have in ALLOWED_HOSTS but it doesn't work... Thank you so much! -
How to use load static (django) in css file for background webkit
How to use {% load static%} in css file for background webkit ? What should i do to get this ? I've tried using {%load static%} in css file but that doesn't work. -
TypeError: 'WSGIRequest' object is not callable
Intento mostrar el modelo de detección de señas en las vistas de django. Pero tengo ese mensaje de error y no me carga la cámara. Estos son mis códigos from django.shortcuts import render from django.http.response import StreamingHttpResponse from PROTOTIPO.step_5_camera import main, center_crop # Create your views here. def home(request): return render(request,'home.html',{}) def sistema(request): return render(request,'Sistema.html',{}) def gen(center_crop): while True: frame=center_crop.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(main): return StreamingHttpResponse(gen(main()), content_type='multipart/x-mixed-replace; boundary=frame') import cv2 import numpy as np import onnxruntime as ort def center_crop(frame): h, w, _ = frame.shape start = abs(h - w) // 2 if h > w: return frame[start: start + w] return frame[:, start: start + h] def main(): # constantes index_to_letter = list('ABCDEFGHIKLMNOPQRSTUVWXY') mean = 0.485 * 255. std = 0.229 * 255. # se crea una sesión ejecutable con el modelo exportado ort_session = ort.InferenceSession("signlanguage.onnx") cap = cv2.VideoCapture(0) while True: # Captura de cuadro por cuadro ret, frame = cap.read() # preprocesamiento de los datos frame = center_crop(frame) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) x = cv2.resize(frame, (28, 28)) x = (x - mean) / std x = x.reshape(1, 1, 28, 28).astype(np.float32) y = ort_session.run(None, {'input': x})[0] index = np.argmax(y, axis=1) letter = index_to_letter[int(index)] cv2.putText(frame, … -
how to deploy django with nginx,guniorn and postgresql
Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine -
Level of logger in django project app view is undefined
When i initialize the logger in the views.py of my app in my django project, the loglevel is undefined althoug i defined it as INFO in the settings.py. I pass the loglevel as a environment variable (I also checked that it is correctly set to INFO by debugging it). When I check the level of the logger in the views.py it always is 0 which means undefined. I also tried to add a root block to the settings and change the name variable to "django" to load the logger both didn't worked. Maybe anyone can tell me what I am missing? Logging config in settings.py: LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py: logger = logging.getLogger(__name__) def teams_overview(request): try: logger.error("error") logger.warning("warning") logger.critical("critical") logger.info("info") logger.debug("debug") output: loglevel of logger: 0 error warning critical Project Strucutre: … -
Django ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
I have a usecase model, I'm trying to update the fields in the model. I have delivery date and estimated delivery date. It seems that delivery date is not able to update alone. If I update estimated delivery along with delivery date it gets updated. otherwise it shows an error: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] my model: class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) usecase_description = models.CharField(max_length=5000) delivery_date = models.DateField() my views: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0], "usecase_types": UsecaseType.objects.all(), "usecase_kpis": Kpi.objects.all()} if request.method == "POST": usecase_type = request.POST['usecase_type'] kpi = request.POST['kpi'] estimated_date = request.POST['estimated_date'] delivery_date = request.POST['delivery_date'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_type_id=usecase_type usecase_details.kpi_id=kpi usecase_details.estimated_date=estimated_date usecase_details.delivery_date=delivery_date usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except Exception as e: print(e) messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="project-name">Usecase Type:</label> <select name="usecase_type" class="custom-select my-1 mr-sm-2" id="usecase_type"> {% for usecase_type in usecase_types %} … -
it is possible to preview template html file before saving it using the Django admin app?
it is possible to preview template Html file before saving it using the Django admin app?? I am try to make overriding template preview button on admin panel but i can't make this I am try to image preview button -
I want to use "if and elif" Inside the Send_mail function in Django
What I want to achieve is I want to use "if and elif" Inside the Send_mail function in Django but an error occurs and I don't know how to fix it... Error message potential arugment cannot appear after keyword aurgument send_mail( subject='New message', message='Access to http://localhost:3000/messagerooms', from_email=settings.EMAIL_HOST_USER, if inquiry_user == self.request.user: recipient_list = post.user.email elif post.user == self.request.user: recipient_list = inquiry_user.email ) -
I am trying to read TID of RFID tag from Chafon CF-RU 5102 in python, i am getting EPC rather than TID
i am following this link, https://github.com/wabson/chafon-rfid, and getting EPC not TID which is a universally unique Tag ID. i am getting 000000000000000000000000 as EPC, whereas E280F336200060000065DDBE is some what expected to be read -
Why isinstance(Test(), MyAbstractClass) return False even if I implement all abstract methods in Test class
From some book, it says when we define a class and implement all abstract methods, even if the class is not inherited from abstract class, the isinstance() check will return True. I try it on my local: from collections import abc class Test: def __len__(self): return 0 print(isinstance(Test(), abc.Sized)) Because there is only one abstract method in abc.Sized class:_len_, the output is True as expected. But when I try to define my own abstract class, it fails: from abc import abstractmethod, ABCMeta Class MyAbstractClass(metaclass=ABCMeta): @abstractmethod def get_size(self):pass class Test: def get_size(self): return 0 print(isinstance(Test(), MyAbstractClass)) The output is False. I need to register it if I want it to be True: MyAbstractClass.register(Test) Why? Why I check it with abs.Sized I don't need to register it but with my own defined abstract class, I have to register it? -
User Roles In Django
I was able to build a Web app that can restrict access to certain pages for authenticated using Django permissionmixedin But I want to divide authenticated users into groups that can be able to access only certain pages. That is even if you are authenticated you can't access all the pages, but can only access the pages that your group fall into. I thought I could set that up when I log into Django admin panel as a super user, but it did not work. Please I need a comprehensive guide on how to do that, both on the user model, views.py and any other file. Because am completely new to this. Am using class based views because am not conversant with function based views. -
loop through two lists of lists and extract elements
I have two lists: list_a contains the number of questions and types I want. There are three types 1* 2* 3* list_b contain all the questions and the types eg 'Q1:1*' and 'Q1 is of type 1*' is considered one question.. So far I have managed to write a code that loops through and randomly selects the number of questions and the type I want. import random list_a = [[1, 1, 1]] # Read this as i want 1 question of type 1*, 1 question of type 2* and 1 question of type 3* list_b = [['Q1:1*','Q1 is of type 1*', 'Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*', 'Q4:2*','Q4 is of type 2*', 'Q5:3*', 'Q5 is of type 3*', 'Q6:3*', 'Q6 is of type 3*']] result = [] # Iterate over each type of question in list_a for i in range(len(list_a[0])): # Determine the number of questions required for this type num_questions = list_a[0][i] # Create a list of the indices of questions in list_b that match this type question_indices = [idx for idx, q in enumerate(list_b[0]) if f":{i+1}*" in q] # Randomly select the required number of questions and their corresponding elements selected_indices = … -
Use xml.etree.elementtree to process xml with xmlns="http://www.w3.org/2005/Atom"
I'm trying to process the data extracted from the web. The decoded raw data was bytes of xml file. I had some old code that just magically worked. However, I'm not sure what they were doing since it's been a while. import urllib, urllib.request url = 'http://export.arxiv.org/api/query?search_query=all:electron+OR+query?id_list=hep-th/9112001&start=0&max_results=2' data = urllib.request.urlopen(url) which could be decoded with data.read().decode('utf-8') which had a file of the form <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <link href="http://arxiv.org/api/query?search_query%3Dall%3Aelectron%20OR%20query%3Fid_list%3Dhep-th%2F9112001%26id_list%3D%26start%3D0%26max_results%3D2" rel="self" type="application/atom+xml"/> <title type="html">ArXiv Query: search_query=all:electron OR query?id_list=hep-th/9112001&amp;id_list=&amp;start=0&amp;max_results=2</title> <id>http://arxiv.org/api/hNIXPXLfJXds3VmSJQ2mnDpmElY</id> <updated>2023-03-20T00:00:00-04:00</updated> <opensearch:totalResults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">194139</opensearch:totalResults> <opensearch:startIndex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startIndex> <opensearch:itemsPerPage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">2</opensearch:itemsPerPage> <entry> <id>http://arxiv.org/abs/cond-mat/0102536v1</id> <updated>2001-02-28T20:12:09Z</updated> <published>2001-02-28T20:12:09Z</published> <title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title> <summary> The effect of the electron-electron cusp on the convergence of configuration interaction (CI) wave functions is examined. By analogy with the pseudopotential approach for electron-ion interactions, an effective electron-electron interaction is developed which closely reproduces the scattering of the Coulomb interaction but is smooth and finite at zero electron-electron separation. The exact many-electron wave function for this smooth effective interaction has no cusp at zero electron-electron separation. We perform CI and quantum Monte Carlo calculations for He and Be atoms, both with the Coulomb electron-electron interaction and with the smooth effective electron-electron interaction. We find that convergence of the CI expansion … -
How to create upload method with authentication FastAPI Users
router = APIRouter( prefix='/reglaments', include_in_schema=True ) router.include_router(reglament_router, dependencies=[Depends(current_user)]) In the route I added dependencies to authentication from FastAPI Users from fastapi_users import FastAPIUsers ... ... ... current_user = fastapi_users.current_user() Below example of how implemented my method @router.post('/{id}/upload', status_code=status.HTTP_200_OK) async def upload_files( relgament_id: int = Path(alias='id'), files: List[UploadFile] = File(description='Reglament documents (pdf, word, excel, etc.)')): '''Upload Reglament Files''' PATH = './static/reglaments' if not os.path.exists(f'{PATH}/{relgament_id}'): path = os.path.join(f'{PATH}/', f'{relgament_id}') try: os.mkdir(path) print(f'[+] Created new directory {relgament_id}, by path {PATH}') except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Can't create new directory by path {path}") for file in files: try: async with aiofiles.open(f'{PATH}/{relgament_id}/{file.filename}', 'wb') as f: while content := await file.read(1024 * 1024): f.write(content) except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='There was an error uploading the file') finally: file.file.close() return {"message": "Successfully uploaded"} but when run this method gives 422 error { "detail": [ { "loc": [ "body", "files" ], "msg": "field required", "type": "value_error.missing" } ] } How to implement upload method with authenctication dependecies from FastAPI Users module -
What is the difference between a Python tuple and a Python list? [duplicate]
I am currently learning about python lists and python tuples. My teacher asked me to list out the differences of the list and the tuple. Can anyone help? -
Python - check if condition is met within a given timeout
I've a script that 1. downloads & push binaries to internal registry (func_to_push_image) and 2. process messages from a section of messaging queue, to see if the push is successful by filtering the messages for a keyword 3. If the push is successful, monitor and process another section of messaging queue, to validate whether those two binaries are installed by looking at the install_status keyword. Timeout for the push action is 2 mins, else fail the script immediately. Timeout for the install action is 1 min, else fail the script with timeout. Messaging queue's output for the binaries installations looks like below. { "location": "root", "md5":"a3288ec45c8d159fbb656972eb4cdfg84jsfbsdf", "fireEye":"v3", "Binaries":[ A:{ "name":"HP-Protect", "version": "v1.3", "effect": "NIL", "install_status":"On Going", } B:{ "name":"Covertur", "version": "v1.0", "effect": "NIL", "install_status":"Installed" }] } Redacted code: registry_timeout = 2 install_timeout = 1 Other variables holding server and partition details. def get_info_from_messaging_queue(server, broker): depending on the partition, returns the messages from the messaging queue. def func_to_push_image(): logic to upload the artifact to the registry. def func_to_check_status_of_installed_binaries(): #This function should Ideally check the status of both binaries has been "Completed" status = False install_status = get_info_from_messaging_queue(server, broker) if install_status['Binaries'][A]['install_status'] == "Completed" and install_status['Binaries'][B]['install_status'] == "Completed": status = True return status … -
Hide Unsupported operand type(s) for -: 'int' and 'NoneType' when no data in database
I am having this issue where I get this error unless there are at least 2 lines of data in the database. Basically what I am doing is marking an item as refunded. I will aggregate all of the fields and then do the math. If I do not have at least 2 lines of data in the database, I always get this error. unsupported operand type(s) for -: 'int' and 'NoneType' The specific line is throwing the error is: total_partial = 0 - total_p_r['refund_amount__sum'] I am not understanding why I am getting NoneType when the default is set to zero on all lines of the models. The code is below. views.py def inventory_management_refund(request): inventory = Inventory.objects.filter(Q(status__contains='REFUNDED') | Q(status__contains='Partial Refund')).order_by('id') totals = Inventory.objects.filter(status__contains='REFUNDED').aggregate( Sum('paid'), Sum('soldprice'), Sum('shipcost'), ) total_p_r = Inventory.objects.filter(status__contains='Partial Refund').aggregate( Sum('refund_amount') ) total_full = 0 - totals['paid__sum'] - totals['soldprice__sum'] - totals['shipcost__sum'] total_partial = 0 - total_p_r['refund_amount__sum'] total_refund_loss = total_full + total_partial return render(request, 'inventory/refunds.html', {"inventory": inventory, "total_refund_loss": total_refund_loss}) template.html <div> <div> <h1 class="text-center">Refunded Items</h1> <hr> </div> {% if inventory.count == 0 %} <h2 class="text-success text-center">There are currently no refunds!</h2> {% endif %} {% if inventory.count > 0 %} <table class="table table-striped"> <thead> <tr> <th>Product</th> <th>Description</th> <th class="invmanrow">Purchase Price</th> <th … -
Label with text copy functionality creation in tkinter
I've got the following tkinter classes that give copy/paste functionality to Entries and copy functionality to Labels. However, I'm not sure how to get the CPLabel class to retrieve the text from the text parameter. When I run the program as is, the CPLabel is packed as evidenced by a space where it should appear, however, no text shows. class CPEntry(Entry): def __init__(self, *args, **kwargs): Entry.__init__(self, *args, **kwargs) self.bind('<Control-c>', self.copy) self.bind('<Control-v>', self.paste) def copy(self, event): self.clipboard_clear() selected_text = self.selection_get() self.clipboard_append(selected_text) def paste(self, event): self.delete(0, END) pasted_text = self.clipboard_get() self.insert(0, pasted_text) class CPLabel(CPEntry): def __init__(self, *args, **kwargs): CPEntry.__init__(self, *args, **kwargs) self.configure(state="readonly", highlightthickness=0, bd=0, cursor="arrow", textvariable=None) self.insert(0, kwargs.get('text', '')) The text that should be displayed is what is within the text parameter. For example, the CPLabel below should display 'Enter a prime number for the value of p'. pLabel = CPLabel(root, text = 'Enter a prime number for the value of p') If you could let me know what I'm doing wrong, or how to get this to work properly that would be awesome. Thanks. -
How to make our program run when my raspberry pi boot up? either using Cron or rc.local
I want to send data from the sensor to the database using raspberry pi. The database is the raspberry pi itself. This is the code I want to run. import time import mysql.connector from bmp280 import BMP280 from datetime import datetime # DATABSE VARIABLE DBHOST = "localhost" #The Host use "localhost" or the database IP DBUSER = "ISTTS" #The user DBPASS = "digital123" #The user password DBDATA = "exampledb" #The database to insert DBTABL = "Test2" #The table to insert # DEVICE ID (int) DID = 1 # SENSOR DELAY DELAY = 5 try: from smbus2 import SMBus except ImportError: from smbus import SMBus mydb = mysql.connector.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBDATA) mycursor = mydb.cursor() # Initialise the BMP280 bus = SMBus(1) bmp280 = BMP280(i2c_dev=bus) while True: now = datetime.now() temperature = round(bmp280.get_temperature(),2) pressure = round(bmp280.get_pressure(),2) print('{}*C {}hPa'.format(temperature, pressure)) time.sleep(DELAY) sql = "INSERT INTO " + DBTABL + " (Date, DeviceID, Temperature, Pressure) VALUES (%s, %s, %s, %s)" val = (now, DID, temperature, pressure) mycursor.execute(sql, val) mydb.commit() I tried to use cron before, but somehow it didn't work. What i put in my Cron is @reboot sudo python3 /home/istts/Desktop/MySQL.py I tried to see the log but didn't find anything related to my … -
why does function does not stop when a exception is raised (Python)
I have a class like this: import threading import time import psutil class TimeoutError(Exception): pass class Performance: def __init__(self, func, time_limit=20, except_return = None) -> None: self.func = func self.except_return = except_return start_time = time.perf_counter() process = psutil.Process() process.memory_info().rss process.memory_info().rss elapsed_time = time.perf_counter() - start_time self.time_limit = time_limit + elapsed_time self.__init_time_waste = elapsed_time def handler(self): with open('Output.txt',mode='a',encoding='utf-8') as f: f.writelines("Time Limited Exceeded!\n") raise TimeoutError("Time Limited Exceeded!") def run(self): def run_func(): timer = threading.Timer(self.time_limit,self.handler) result = [] start_time = 0 before_memory = 0 after_memory = 0 elapsed_time = 0 timer.start() try: start_time = time.perf_counter() process = psutil.Process() before_memory = process.memory_info().rss result = self.func() after_memory = process.memory_info().rss elapsed_time = time.perf_counter() - start_time - self.__init_time_waste except Exception as e: print(e) timer.cancel() return self.except_return else: timer.cancel() with open('Output.txt',mode='a',encoding='utf-8') as f: f.writelines(f"Executing Time: {elapsed_time:.5f} \n") f.writelines(f"Memory Used: {after_memory - before_memory} bytes \n") print(f"Executing Time: {elapsed_time:.5f}") print(f"Memory Used: {after_memory - before_memory} bytes") return result return run_func() This class is used to limit the run time of a function and compute the memory used. But when the exception is raised, the self.func still execute and doesn't terminated. Please help me :((( -
How to create a stub Python package for PyCharm?
Let's say we have a builtin module car. We have no autocomplete in PyCharm for it. It has interface: def getState(id, optional_id = None): pass def log(value): pass So, end usage would be: import car car.getState(5) car.log('Test') How to create a package and join it into PyCharm to make autocomplete work for a described interface? If I created a package car-stub with car.py file, and installed it in the project, I will have to use code line from car-stub import car. But how to make it in such a way it would not require code changes? The system would provide autocomplete for import car.