Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django backend server runtime error using gunicorn
I developed backend server using django python framework. But, It didn't work. I have searched this error in websites, but I couldn't find answer. Here is error log: 11:58:38 master systemd[1]: Starting Gunicorn Service... 11:58:38 master systemd[1]: Started Gunicorn Service. 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Starting gunicorn 20.1.0 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Listening at: http://127.0.0.1:8001 (2705621) 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Using worker: eventlet 11:58:38 master gunicorn[2705626]: [2023-03-20 11:58:38 +0900] [2705626] [INFO] Booting worker with pid: 2705626 11:59:08 master gunicorn[2705621]: [2023-03-20 11:59:08 +0900] [2705621] [CRITICAL] WORKER TIMEOUT (pid:2705626) 11:59:08 master gunicorn[2705626]: Stack trace (most recent call last): 11:59:08 master gunicorn[2705626]: #16 Object "[0x7fd822b8c5b7]", at 0x7fd822b8c5b7, in 11:59:08 master gunicorn[2705626]: #15 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a96cbf, in greenlet::UserGreenlet::g_switch() 11:59:08 master gunicorn[2705626]: #14 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a969a1, in greenlet::UserGreenlet::g_initialstub(void*) 11:59:08 master gunicorn[2705626]: #13 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a95a16, in greenlet::UserGreenlet::inner_bootstrap(greenlet::refs::_OwnedGreenlet<_greenlet, &greenlet::refs::GreenletChecker>&, greenlet::refs::OwnedReference<_object, &greenlet::refs::NoOpChecker>&) 11:59:08 master gunicorn[2705626]: #12 Object "/home/master/envs/guide/bin/python", at 0x5f52b1, in PyObject_Call 11:59:08 master gunicorn[2705626]: #11 Object "/home/master/envs/guide/bin/python", at 0x50b32b, in 11:59:08 master gunicorn[2705626]: #10 Object "/home/master/envs/guide/bin/python", at 0x5f60c2, in _PyFunction_Vectorcall 11:59:08 master gunicorn[2705626]: #9 Object "/home/master/envs/guide/bin/python", at 0x569d89, in _PyEval_EvalCodeWithName 11:59:08 master gunicorn[2705626]: #8 Object "/home/master/envs/guide/bin/python", at 0x56bbe0, in _PyEval_EvalFrameDefault 11:59:08 master … -
JSONDecodeError Expecting value: line 1 column 1 (char 0) when receiving via Bluetooth
I am transmitting a JSON payload from an Arduino microcontroller and attempting to receive it using a Python script: import bluetooth #pybluez import json sensor_address = "18:D9:31:YY:C7:4A" socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) socket.connect((sensor_address, 1)) buffer = "" print("Listening...") while True: data = socket.recv(1024) buffer += str(data, encoding='ascii') print(buffer) # used to check json payload try: data = json.loads(buffer) print("Received:", data) buffer = "" except json.JSONDecodeError as e: print(e) continue Examining the value stored in buffer before entering the try statement, I see what appears to be perfectly valid JSON: {"a_x":957.5195,"a_y":-0.488281,"a_z":315.918,"g_x":-0.625954,"g_y":-1.305344}{"a_x":961.914,"a_y":-1.953125,"a_z":297.8516,"g_x":-2.816794,"g_y":2.572519}{"a_x":964.8437,"a_y":3.417969,"a_z":303.2227,"g_x":-1,"g_y":0.374046} However the result of my script is only Expecting value: line 1 column 1 (char 0) repeatedly. Why doesn't the code inside the try statement execute once a complete payload has been received? My hunch is that at no time does a valid JSON payload appear in buffer, but instead valid payloads appear along with incomplete payloads. Is it possible to use a regular expression to extract a valid payload from a string? -
why iam run "make" command to install tlwn722n driver, and error at "prandom_u32" [closed]
why iam run "make" command to install tlwn722n driver, and error at "netif_napi_add" cd rtl8188eus make <<ERROR make install -
¿How to config WAF to API GATEWAY/LAMBDA with serverless framework?
I need set a AWS WAF to AWS API GATEWAY with serverless framework. I tried with this plugin (https://www.serverless.com/plugins/serverless-associate-waf) but don't work. I added this code with serverless.yml : plugins: - serverless-associate-waf - serverless-plugin-bind-deployment-id custom: associateWaf: name: Development-waf version: V2 #(optional) Regional | V2 but when I launch deploy, this return an error: Error: The CloudFormation template is invalid: Unresolved resource dependencies [ApiGatewayRestApi] in the Outputs block of the template -
python GIL: Why need Lock when making changes to collections?
Sorry one question, everyone knows Python has GIL, so only one thread is spinning at any one point in time. https://opensource.com/article/17/4/grok-gil This said, then why do we need lock when accessing/modifying collections? Appending or popping elements from a list for example. Or updating a dictionary? Operations like list.sort() also is atomic. I am guessing the answer be: Are you sure any of the operations that you're performing is "Atomic"? If not it can be pre-empted (Preemptive multi-tasking) Thus, in general, because you're unsure how things are implemented under-the-hood, safer to just lock.acquire? Thanks in advance. -
Django Channels AsyncWebsocketConsumer render template
I am trying to send HTML over a websocket via Django channels. It worked fine with a non-asynchronous Websocket Consumer, but upon converting everything to Async I am left with this last error. Here is the problematic code segment and error message: context = { "online_users": redis_instance.smembers(redis_online_name) } await self.channel_layer.group_send( self.room_group_name, { 'type': 'online_users_list', 'html': render_to_string("partials/message/hx_online_users.html", context), } ) server ERROR Exception inside application: 'coroutine' object is not iterable Traceback (most recent call last): File "/.../python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/.../python3.11/site-packages/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/.../python3.11/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/.../python3.11/site-packages/channels/generic/websocket.py", line 173, in websocket_connect await self.connect() File "/.../chat/consumers.py", line 63, in connect 'html': render_to_string("partials/message/hx_online_users.html", context), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Writing an asynchronous view function in django for my form
I want to write an async function in django. My view is the same for my GET request and for my POST request (form). My goal is to make my POST asynchronous, so when I send my form, the page does not remain loading and waiting for the server's response. In my POST request I send my form data to an API so I want this function in a coroutine, but it's not working properly. I'm using uvicorn to run my application with the default asgi configuration. I will put my view and my api function here: async def payment_return_view(request): if request.method == 'POST': # do process form form = PaymentReturnForm(request.POST) if form.is_valid(): payment = get_payment_return_api_data(form) # perform request to payment return through API r = await asyncio.gather(*[payment_return(payment)]) request.session[payment.returnID] = r.dict() return redirect("payment_return_result", internal_id=payment.returnID) else: # get params from request params = request.GET payments = get_payments(params).dict() payments = payments.get('entries', []) form = PaymentReturnForm() context = { 'form': form, 'payments': payments, 'params': params } return render(request, 'payment-return.html', context) And this is my async funtion: async def payment_return(payment_return: PaymentReturn) -> Result: d = payment_return.dict() async with aiohttp.ClientSession() as session: async with session.post( f"{API_URL_BASE}/payment/return", data=json.dumps(d, cls=DjangoJSONEncoder), headers={'Content-Type': 'application/json'} ) as r: data = … -
Get the string in an span id tag, wehn running python selenium
I want to extract the word "In stock" from the element. The tag looks like this: <span id="quantitySpan">" in stock" <img class="quantitySpanImg" src="https://d3m9l0v76dty0.cloudfront.net/system/photos/436808/original/34f362ca4ecee94ab2262e159a8ce432.jpg?1588592491"> <-span> I tried to get the string using: driver.find_element(By.ID, "quantitySpan") but it didn't work. I tried by XPath but I'm still not getting the string. driver.find_element(By.XPATH,"/html/body/div[4]/div[2]/div/form/div[2]/div[1]/div[2]/div[2]/span") -
Python, How can I dynamically define a variable when it is imported
I don't actually know if this is possible but I would like to do the following: foo.py: # foo.py my_var = "hello_world" def fancy(s): return s.replace("_"," ").replace("hello", "Hola") main.py: # main.py from foo import my_var, my_var_fancy print(my_var) print(my_var_fancy) And get an output like: >> hello_world >> Hola world Note that I do not want to explicitly define "my_var_fancy" anywhere. I would like I to be dynamically defined when imported using the fancy function. I suspect this could possibly be accomplished with decorators or something similar to a hasattr() check on the module but I'm not sure how. -
Password reset confirm/Password reset request-Django Rest api
I am trying to make reset password functionality.I am able to make the password reset request as I receive the user email for which password need to be changed and successfully send the user the email to reset it(via postman).The problem is when I open the reset mail it directs to the password reset confirm where the user enter the new password to replace the old it in the database.I am unable to handle it with both the GET and POST methods.GET is to display the field where user can enter the new password and POST for posting the request and updating the custom user model. serializers.py from rest_framework import serializers from django.contrib.auth.hashers import make_password from .models import CustomUser class SignUpUserSerialzer(serializers.ModelSerializer): password = serializers.CharField(max_length=100, write_only=True) def validate_password(self, password): return make_password(password) class Meta: model = CustomUser fields = '__all__' class ChangePasswordSerializer(serializers.Serializer): model = CustomUser """ password = serializers.CharField(max_length=100, write_only=True) def validate_password(self, password): return make_password(password) class Meta: model = CustomUser fields = ['password'] urls.py from django.urls import path,include from . import views # from .views import ChangePasswordView urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.custom_login, name='login'), path('logout/', views.custom_logout, name='logout'), path('user/', views.user_profile, name='user_profile'), path('activate/<uidb64>/<token>', views.activate, name='activate'), path("passwordreset/", views.password_reset_request, name="password_reset"), path('reset/<uidb64>/<token>/', views.passwordResetConfirm, name='password_reset_confirm'), ] … -
Django limit records (options) for ModelChoiceField
I have a Model Reader with ModelChoiceField favourite_book which is a Foreign key. It is a DropDown menu and user can choose one from 40.000 possible options (records in the database). There is a problem when editing this Model object and this specific field because DropDown is being populated with all the records from the database which takes too much time and memory. So, I have to find a way to somehow render this field with a matching option (that user has previously selected and saved in DB) alone and not with thousands of other options. I tried: readerForm.fields['books'].initial = Books.objects.get(id=url) but initial doesn't work with bound forms. I have $.ajax request that will later filter those 40.000 options based on input so user can choose some other option if needed. -
Url not found on ajax reqest Django
I want to trigger on update view via ajax call but showing the URL is not found. Any help would be appreciated Ajax: $(document).on("change", "#id_device_type", function() { var id = $(this).val(); $.ajax({ url: '/register-non-device/view/', type: "GET", dataType: 'json', data: $(this).val() }); }); url: path('register-non-device/view/<int:pk>/', RegisterNonDeviceView.as_view(), name='register-non-device') View: class RegisterNonDeviceView(UpdateView): model = AnticipatedNonDevice form_class = AnticipatedNonDeviceForm template_name = 'anticipated_non_device.html' success_url = reverse_lazy('app:po-search-non-device') -
I am trying to calculate the product price before the discount
I am trying to calculate the product price before the discount through the product price and the discount percentage The question is: how do I write this equation price / (1-discount%) into the template in Django Example: <span class="old-price">{{......}} L.E</span> <span class="old-price">{{......}} L.E</span> -
IndexError in the cross_entropy function during training of a neural network,? target 23 is out of bound
IndexError Traceback (most recent call last) <ipython-input-56-7660551ed736> in <module> 162 163 # Call grid search function --> 164 grid_search(train_loader, test_loader, optimizers, learning_rates, activation_fns, hidden_sizes_list, use_batch_norm_list, use_l1_l2_reg_list, use_dropout_list) 4 frames /usr/local/lib/python3.9/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing) 3024 if size_average is not None or reduce is not None: 3025 reduction = _Reduction.legacy_get_string(size_average, reduce) -> 3026 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) 3027 3028 IndexError: Target 23 is out of bounds. below is my code: # Define function to train the model def train(model, criterion, optimizer, train_loader): start_time = time.time() losses = [] for epoch in range(10): running_loss = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) optimizer.zero_grad() output = model(images) loss = criterion(output, labels) loss.backward() optimizer.step() running_loss += loss.item() losses.append(running_loss/len(train_loader)) print(f"Epoch {epoch+1}, Loss: {running_loss/len(train_loader):.3f}") end_time = time.time() print(f"Training time: {end_time - start_time:.3f} seconds") plt.plot(losses) plt.xlabel('Epoch') plt.ylabel('Loss') plt.show() -
Python "on_destroy" class method
I am wondering if there is a way to call a method before the object is finally "destroyed" - like some sort of event. I am using a class and a static method. Since it is not an instantiated object, I cannot use del and modify __del__ on it. Is the object garbage collected at all if not instantiated? For example: class Test: @staticmethod def say_hello(): print("Hello") def on_destroy(self): print("Object was destroyed...") Test.say_hello() What I want to achieve is that the method on_destroy will fire after say_hello since I am using a static method. I tried using __del__ and it is not being called. Thansk for the help. -
allauth/dj_rest_auth - How come Google OAuth2 works without backend server knowing client_id, client_secret
I tried to implement Google OAuth2 authentication in this project. Backend server runs Django and DRF. To login using rest API, I use dj_rest_auth library. This is roughly how it works: front-end generates auth url like https://accounts.google.com/o/oauth2/auth/i... user authenticates frontend receives access_token access_token is being sent to API to {{API_URL}}auth/google/ backend fetches profile information using this token and saves user I needed to register SocialApp with Google provider but it looks like it is only used for profile fetching. In fact I just used client_id="xxx" and no client_secret. I would expect that the access_token is somehow verified using the client_id and client_secret but obviously it works without them. Is that safe? -
iterate over a set of given URLs and gather the output of data in CSV formate with request and BS4
iterate over a set of URLs and gather the output of data in CSV formate how to iterate over a set of 700 Urls to get the data of 700 digital hubs in CSV (or Excel-formate)- see the page where we have the datasts: shown here https://s3platform.jrc.ec.europa.eu/digital-innovation-hubs-tool with the list of urls like here; https://s3platform-legacy.jrc.ec.europa.eu/digital-innovation-hubs-tool/-/dih/3480/view https://s3platform-legacy.jrc.ec.europa.eu/digital-innovation-hubs-tool/-/dih/13281/view https://s3platform-legacy.jrc.ec.europa.eu/digital-innovation-hubs-tool/-/dih/1417/view https://s3platform-legacy.jrc.ec.europa.eu/digital-innovation-hubs-tool/-/dih/1349/view and so on and so forth question: can we apply this to the similar task too: see the collection of data as digital hubs: i have applied a scraper to a single site with this- and it works - but how to achieve a csv-output to the scraper that iterates on the urls can we put the output into csv too - while applying the same technique!? i want to pair web scraped paragraphs with the most recent scraped heading from the hubCards: I am currently scraping the hubCards as single pages to find the method, however, I would like to get all the 700 Cards scraping scraped with the headings so I can see the data together in a CSV file. i want to write it to results to an appropiate formate - which may be a csv file. Note: we … -
gmaps figure not displaying when using python and vsCode
I'm trying to use python to display a google map. the eventual goal is to put a heatmap overlay of some data on it, but for now I'm just trying to get it to show me a map. here is the code: import gmaps import googlemaps from IPython.display import display # Read the API key from a file with open('api_key.txt') as f: api_key = f.readline().strip() # Create a client object with the API key gmaps_key = googlemaps.Client(key=api_key) # Set the center of the map center = (39.28, -76.61) # Create the map with the center and zoom level fig = gmaps.figure(center=center, zoom_level=13) # Display the map fig display(fig) at first, I was trying to run it from just the python console in vsCode (python 3.11.2), running in windows 10. some googling seemed to indicate that I needed to use a Jupyter notebook, so I did that within vscode and now my python code is running from the notebook (extension: ipynb). I still have no google map being displayed. I read that I may need to enable widgets in in bash/jupyter with jupyter nbextension enable --py widgetsnbextension but that gives an error that jupyter is not installed. I feel like I'm … -
Listening for HTMX events with Alpine.js in Django
Django templates can listen for events from HTMX via listeners added to the Javascript part of code. In this case I want to change DOM element(s) after an update on the page. Below works fine: document.body.addEventListener('htmx:afterSwap', (() => { // get input element, clear its value })) I'm using Alpine.js which helps handling dynamic parts on the client side. I want to connect it to HTMX events since it apparently picks up custom events. Unfortunately, when trying to subscribe to any HTMX event, e.g. htmx:after-swap in <form x-on:htmx:after-swap="console.log('event received')" hx-post="{% url 'my_url' %}" hx-target="#responses" > I have no output in the console. Do I need to first trigger Alpine's 'custom event' from plain Javascript (e.g. in the working addEventListener block above) or can I connect HTMX with Alpine.js directly? I have tried: various cases combinations (I gather kebab is the way for Alpine.js); tried various HTMX events such as htmx:load; replaced x-on with @; found HTMX+Alpine.js examples elsewhere (for instance involving x-data prefix) but none of them worked for me. I would like to understand the process, thank you. -
Sample and hold using Pandas
I have a Pandas dataframe that looks like this ID Time Value 0 1 10 1.0 1 2 10 2.0 2 1 20 NaN 3 3 20 4.0 4 1 30 NaN 5 2 30 NaN 6 4 30 NaN I want to do sample and hold for each ID, using the last known non-null value to impute some of the nulls based on the parameter max_time. For every row where Value is null and time is t, if there is a row with the same ID with time t_other such than t-max_time <= t_other <= t, then I want to replace the Value of my row with the Value of the row with the max t_other that satisfies this constraint. For example, in the table shown above, if max_time=10, then for ID = 1 at Time = 20 we have a null Value which can be filled by the value at Time = 10. So the result would become ID Time Value 0 1 10 1.0 1 2 10 2.0 2 1 20 1.0 3 3 20 4.0 4 1 30 NaN 5 2 30 NaN 6 4 30 NaN The other nulls don't have a value in the … -
opencv error conv_winograd_f63.cpp ubuntu 22 python3.10 cv2 although works on 2nd machine
I have a development machine working with ubuntu 22, python 3.10 and cv2; when I try to replicate on another machine then I get runtime error: from section calling age prediciton from haarclassifier and age_net.caffemodel: line 118 return age_net-forward() cv2.error: OpenCV(4.7.0-dev) (note this after building files from source orcv2 4.7.0 or 4.6.0 same result) /home/art/opencv_build/opencv/modules/dnn/src/layers/cpu_kernels/conv_winograd_f63.cpp:401: error: (-215:Assertion failed) CONV_WINO_IBLOCK == 3 && CONV_WINO_ATOM_F32 == 4 in function 'winofunc_BtXB_8x8_f32' I have tried various permutations of installing opencv-python or opencv-contrib-python or building and compiling the opencv files from source, always with the same result. Works on the original machine but always throws this error on the second machine when running the same python code. I have searched online generally and in stackoverflow and I don't see anyone noting this error. Anyone know? Tried to duplicate machine where it is working and various permuations of installing opencv either directly: pip3 install opencv-python or pip3 install opencv-contrib-python or build the opencv files from source, which is generally to build the dependencies: sudo apt install build-essential cmake git pkg-config libgtk-3-dev \ libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \ libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \ gfortran openexr libatlas-base-dev python3-dev python3-numpy \ libtbb2 libtbb-dev libdc1394-dev clone the repositories: $ … -
Sort Columns by assigned column
I have a following code: import bs4 as bs import requests import yfinance as yf import datetime import pandas as pd import time starttimer = time.time() resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = bs.BeautifulSoup(resp.text, 'lxml') table = soup.find('table', {'class': 'wikitable sortable'}) tickers = [] for row in table.findAll('tr')[1:]: ticker = row.findAll('td')[0].text tickers.append(ticker) tickers = [s.replace('\n', '') for s in tickers] start = datetime.datetime(2020, 1, 1) end = datetime.datetime(2022, 1, 1) data = yf.download("GOOGL", start=start, end=end) print(data) eodPrices = pd.DataFrame(data=data); percentageChange = round(eodPrices.pct_change()*100,2).shift(-1) percentageChange.sort_values(by=['Close'],inplace=True) dataframe = pd.DataFrame(percentageChange,columns = ['Close']) print(dataframe) The code gets data for required ticker/s from yfinance module, then sort (Ascending) them. I receive following response: I have several issues with this response: I don't see a ticker in the response and when I try to download more tickers I receive following error: ValueError: The column label 'Close' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level. I don't know how to fix this. My desired response should be as following: Current date formatting: I'd like to have just a date e.g. "2020-03-13". It seems to be hardcoded and I can't change it, is there a way how to do it? Thank … -
QSlider value change interrupts audio playback of QMediaPlayer [closed]
I am having difficulties using PySide6 to control the playback of music. I have implemented a slider to allow the user to control the progress of the music, but I am having issues: when the slider is used, the music stops and does not resume. How can I ensure that the slider works properly with the music playback in PySide6? https://drive.google.com/file/d/10f0RBy4jzDH1eyd5Zb52CfZyWEhm9x4b/view?usp=share_link pause the music while moving, then when I release the slider it resumes the music. I searched for codes like this on the internet but none working well either import sys from PySide6.QtCore import Qt, QUrl from PySide6.QtGui import QPalette from PySide6.QtWidgets import QApplication, QMainWindow, QSlider, QPushButton, QHBoxLayout from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput import time class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(200, 200, 300, 200) self.player = QMediaPlayer() self.audio = QAudioOutput() self.player.setAudioOutput(self.audio) self.player.setSource(QUrl.fromLocalFile('./muzgas/505.mp3')) self.button = QPushButton("play", self) self.button.setGeometry(50, 100, 100, 30) self.slider = QSlider(Qt.Horizontal, self) self.slider.setGeometry(50, 50, 200, 20) self.slider.sliderMoved.connect(self.jump_to_time) self.button.clicked.connect(self.play) def play(self): time.sleep(0.5) self.player.play() self.audio.setVolume(0.01) self.slider.setRange(0, self.player.duration() // 1000) def jump_to_time(self, position): print(position) self.player.setPosition(position * 1000) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec()) -
Pycharm can't recognize apps that added using manage.py startapp django
when I add app to my django project by using 'python manage.py startapp [app_name]' and add app_name to my INSTALLED_APPS in django settings pycharm can't recognized imports from that apps (when I run my server, it runs without error). What should I do? I upload some images below for more detials my working directory is like this: -ToDoApp-DRF-CBV[PyCharm Working Directory] --core ----core ----manage.py ----accounts ----blog --gitignore --... when I change my working directory to 'core' it can find modules (which is normal) but I can't do that because I have VCS in my current working directory and other code editors like VSCode find my apps for imports and only PyCharm can't recognized them. -
I there any way to use PySocks in multithread? RuntimeError: can't register atexit after shutdown
I am trying to use telethon library with porxy(for proxy using PySocks) but getting error RuntimeError: can't register atexit after shutdown. Without proxy everything works well. Here is my code: import asyncio import subprocess from threading import Thread, Event from telethon import TelegramClient, events, sync from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.functions.messages import CheckChatInviteRequest from telethon.tl.functions.channels import GetFullChannelRequest from telethon.tl.functions.account import UpdateUsernameRequest from telethon.tl.functions.photos import UploadProfilePhotoRequest from telethon.tl.functions.account import UpdateProfileRequest from opentele.td import TDesktop from opentele.api import API, UseCurrentSession, CreateNewSession import socks #import python_socks numbers = ["380666666666", "380666666667"] my_proxy = { 'proxy_type': socks.HTTP, 'addr': 'someproxyip', 'port': 12321, 'username': 'someusername', 'password': 'somepassword' } def main(thread_cntr): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) print(f"Inside {thread_cntr}") number = numbers[thread_cntr] print(f"inside {thread_cntr}") api = API.TelegramIOS.Generate() print("gen") client = TelegramClient(f"{number}", api=api, loop=loop, proxy=my_proxy) print("client") client.connect() if not client.is_user_authorized(): print("No auth") code_request = client.send_code_request(phone=number, force_sms = True) print(code_request) client.sign_up(phone=number, code=input("Code: ")) client.start() me = client.get_me() print(me.username) return True threads = [] thread_cntr = 0 for num in numbers: threads.append(Thread(target=main, args=(thread_cntr, ))) thread_cntr += 1 print(threads) for thread in threads: print("\nStarting thread") thread.start() print("Thread started") I also tied python-socks[asyncio] instead of PySocks but get same error. If join all threads with thread.join() everything also works but in single thread which is …