n. A piece of art made by sticking various different materials, aka PHENOMENA Magazine


Common SSL Issues on Python and How to Fix it
SSL certificate_verify_failed errors typically occur as a result of outdated Python default certificates or invalid root certificates. When client receives the server’s certificate, it begins chaining that certificate back to its root. It will begin by following the chain to the intermediate that has been installed, from there it continues tracing backwards until it arrives at a trusted root certificate. If the certificate is valid and can be chained back to a trusted root, it will be trusted. If it can’t be chained back to a trusted root, the browser will issue a warning about the certificate.   Common issues :  CERTIFICATE_VERIFY_FAILED [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate. HTTPSConnectionPool(host='' , port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))   How to fix it :  We will have several ways to fix this issue in this article.  We will skip the SS certificate check in the first three solutions.  For the fourth solution, we are going to install the latest CA certificate from certifi. Common Quick Fixes for All OS : import ssl import certifi from urllib.request import urlopen request = "" urlopen(request, context=ssl.create_default_context(cafile=certifi.where()))   Or we can try it in several ways as per in below articles 1. Create unverified context in SSL import ssl context = ssl._create_unverified_context() urllib.request.urlopen(req,context=context)   2. Create unverified https context in SSL import ssl ssl._create_default_https_context = ssl._create_unverified_context urllib2.urlopen(“”).read()   3. Use requests module and set ssl verify to false requests.get(url, headers=Hostreferer,verify=False) * It's not recommended to use verify=False in your organization's environments. This is essentially disabling SSL verification. Sometimes, when you are behind a company proxy, it replaces the certificate chain with the ones of Proxy. Adding the certificates in cacert.pem used by certifi should solve the issue. I had similar issue. Here is what I did, to resolve the issue - Find the path where cacert.pem is located - Install certifi, if you don't have. Command: pip install certifi import certifi certifi.where() C:\\Users\\[UserID]\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\certifi\\cacert.pem Open the URL on a browser. Download the chain of certificates from the URL and save as Base64 encoded .cer files. Now open the cacert.pem in a notepad and just add every downloaded certificate contents (---Begin Certificate--- *** ---End Certificate---) at the end.   4. Update SSL certificate with PIP It is likely that the SSL certificate issued by the server is not trusted on your client. To fix this, you can either use a trusted certificate from a recognized certificate authority on the API end, or add the certificate authority from your API to your client. if the error stay, try these commands to update your SSL certificate libs With PIP. All we would have to do is to update our SSL certificate directory with the following piece of code: if older version of python3 pip install –upgrade certifi if newer version of python3 python -m pip install --upgrade certifi What this command does is update our system’s SSL certificate directory. This will ensure that your client has the latest version of the library, which includes a set of trusted root certificates that may be needed to verify SSL certificates.   5. Update SSL certificate with certifi (MacOS only) All we would have to do is to run command with the following piece of code: - Press "command + space" button or open Spotlight - type "Install Certificates.command" What this command does is update our system’s SSL certificate directory for MacOS. Unable to get local issuer certificate when using requests here is my code import requests; url='that website'; headers={ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Language':'zh-CN,zh;q=0.... HTTPSConnectionPool: Max retries exceeded with URL (Caused by SSLError) I am trying to make an HTTPS request to a URL using Python requests library and certifi library as follows: import certifi url = '' response = requests.get(url, verify= CERTIFICATE_VERIFY_FAILED error Python Django error: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)> Exception Location: /usr/lib/python3.8/u... Why do I receive 'unable to get local issuer certificate (_ssl.c:997)' When sending a request to a specific URL I get an SSL error and I am not sure why. First please see the error message I am presented with: requests.exceptions.SSLError: HTTPSConnectionPool(host='di... SSLError: max retries exceeded with url error? How to fix this? I am attempting to scrape text off of websites, and I am using the requests module to do so. With the given code (Facebook as an example here) requests.get('') I receive back the
python · Aug. 29, 2023, 8:15 p.m.
ssl python
Troubleshooting for Django
1) 장고 패스워드 재설정 시 이메일이 안보내지는 경우 패스워드 리셋 이메일은 active user(is_active가 true) 이면서 사용가능한 패스워드가 설정되어 있는 유저인 경우(has_usable_password 도 true) 에만 전송이 된다. 즉 gmail이나 네이버 oauth 등으로 가입한 유저의 경우에는 패스워드를 직접 타이핑하여 설정한 경우가 아니기에 패스워드 리셋 이메일이 안 보내지는 것이다. 아무 오류도 안뜨고 마치 전송된 것처럼 나올 수 있으므로 주의. Django: reset-password not sending email I am using the Django password reset. I have this code in my EMAIL_USE_TLS = True EMAIL_HOST = '' EMAIL_PORT = 587 EMAIL_HOST_USER = ''   2) 장고 특정 app에 다국어 추가 1. 해당 app에 locale 폴더를 만든다. 2. 가상경로에서 해당 app 경로로 이동 3. 다음 명령을 실행 django-admin makemessages -l ja 4. 컴파일 django-admin compilemessages How do I run makemessages so it includes some apps that are outside the Django project? I have the following structure: . ├── apps │   ├── app1 │ │ ├── app1 │ │ └── │   ├── app2 │ │ ├── app2 │ │ └── ├── my_django_project │   ├── appA │   ├── appB │  ...   3) requirements.txt 를 통한 패키지 종속성 관리 현재 환경에서 설치한 패키지 확인 pip freeze 설치한 패키지 목록을 파일에 담기 pip freeze > requirements.txt 패키지 설치 pip install -r requirements.txt ssl 오류가 발생할 경우에는 pip install --trusted-host --trusted-host -r requirements.txt   4) django management 시스템 안에서 내 명령어 만들고 사용하기 app들을 import하여 만든 코드를 서버시작없이 콘솔에서 테스트 또는 실행하고 싶을 때 유용함. 그냥 Run 해버리면 import된 모듈을 찾을 수 없다고 나온다. shell 명령을 쓰지않아도 되어서 편하다 1. 폴더구조를 아래와같이 만들어야 한다 $ tree CallCenter ├── ├── ├── ├── management │ └── commands 2. 이제 commands 폴더 안에 내가 쓰고자 하는 명령어의 이름으로 python 파일을 작정한다 여기서는 CallCenter/management/commands/ from import Client from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse from CallCenter.models import Campaign from import BaseCommand def create_xml(campaign): # Creates XML response = VoiceResponse() response.say(campaign.campaign_text) return response class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("--campaign-id", required=True, type=int) def handle(self, campaign_id, **options): campaign = Campaign.objects.get(pk=campaign_id) xml = create_xml(campaign) print(xml) 3. 아래와 같이 실행하면 된다 $ python make_call --campaign-id=1 How to run a python script in Django? I am new to Django, and I'm trying to import one of my models in a script as we do it in I'm getting an error: Traceback (most recent call last): File "CallCenter\", line ...   5) django를 이용한 소셜 로그인 소셜로그인의 양대산맥: GitHub - pennersr/django-allauth: Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication. Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication. - GitHub - pennersr/django-allauth: Integrate... GitHub - python-social-auth/social-app-django: Python Social Auth - Application - Django Python Social Auth - Application - Django. Contribute to python-social-auth/social-app-django development by creating an account on GitHub. app을 등록한 후 사용하면 된다 트위터: Twitter Developers   JavaScript is not available. We’ve detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser to continue using You can see a list of supported browsers in our Help Center. Help Center Term 네이버: 애플리케이션 - NAVER Developers 애플리케이션 - NAVER Developers 네이버로 연동된 app목록은 여기서 확인가능 Apps : NAVER Account 네이버 네이버에 로그인 하고 나를 위한 다양한 서비스를 이용해 보세요 구글: Google Cloud Platform Sign into continue to Google Cloud PlatformEmail or phoneForgot email?Type the text you hear or seeNot your computer? Use Guest mode to sign in privately. Learn moreNextCreate account 이중 가장 까다로웠던건 네이버연동. 첨에 신청했다가 어떤목적 사이트인지 기술안했다고 반려당하고 가입시 선택사항으로 이름을 넣어놨는데 사용목적이 안나왔다고 반려당하고 선택사항삭제하고 별명을 필수로 넣었는데 어디에 쓰이는지 알수없다고해서 캡쳐후 재신청하고 검수 승인까지 좀 걸렸었다.
python · June 27, 2023, 10:27 a.m.
How to Draw 4-Leaf Clover Using a Turtle in Python
This graphics system is a great way for beginners to conquer both Python and 2D drawing.   Code: import turtle as t def draw_leaf(color): t.begin_fill() t.color(color) t.left(50) t.forward(60), 190) t.right(100), 180) t.forward(50) t.left(50) t.end_fill() def draw_stem(degree, length, color): t.rt(degree) t.pensize(5) t.color(color) t.fd(length) t.back(length) n = 4 color = 'green' t.setup(430, 430) draw_stem(90, 150, color) t.pensize(2) for i in range(n): draw_leaf(color) t.home() / n) * (i + 1)) t.pu() t.mainloop()   Result:  
python · June 22, 2023, 8:29 p.m.
Turtle clover
Using Selenium: How to keep logged in after closing the driver in Python
I tried the below code on my Mac, and it worked perfectly fine. I don't need to login again. from selenium import webdriver from import Options from import WebDriverWait chrome_options = Options() chrome_options.add_experimental_option("detach", True) chrome_options.add_argument("user-data-dir=/tmp/oriel") # chrome_options.add_argument("--start-maximized") browser = webdriver.Chrome(options=chrome_options) wait = WebDriverWait(browser, 10) url = "" browser.get(url) browser.implicitly_wait(1) print(browser.title) For window you can try changing the path as below chrome_options.add_argument("user-data-dir=C:\\Users\\Oriel\\AppData\\Local\\Google\\Chrome\\User Data\\Default")   Ref. Using selenium: How to keep logged in after closing Driver in Python I want to get my Whatsapp web ( logged in, at the second time opening the Whatsapp web on chrome driver. Following is my code based on Python need your help. from selenium import How to start ChromeDriver with existing login GroupsSign inGroupsSelenium UsersConversationsLabelsAboutSend feedbackHelpPrivacy • TermsHow to start ChromeDriver with existing login 11741 viewsChromeJavaSkip to first unread messageTiếu Thủyunread,Nov 26, 2014, 11:59:10 PM11/26/14Reply to auth  
python · June 2, 2023, 3:23 a.m.
Python Basic
1. Write a Python program to check whether a given number is a narcissistic number or not. For example, 371 is a narcissistic number; it has three digits, and if we cube each digits 33 + 73 + 13 the sum is 371. Other 3-digit narcissistic numbers are 153 = 13 + 53 + 33 370 = 33 + 73 + 03 407 = 43 + 03 + 73. def is_narcissistic_num(num): return num == sum([int(x) ** len(str(num)) for x in str(num)]) for x in range(100, 1000): if is_narcissistic_num(x): print(x) Result: 153 370 371 407   2. Print a customized calendar. import calendar import re yy = int(input("Enter the year number: ")) mm = int(input("Enter the month number: ")) calendar.setfirstweekday(calendar.SUNDAY) x = calendar.month(yy, mm, 3) pattern = rf" {yy}\n" x = re.sub(pattern, "{}----------------------------\n".format(pattern), x) print(x) Result: Enter the year number: 2023 Enter the month number: 5 May 2023 ---------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Process finished with exit code 0 Ref. Print a calendar starting from today's date I want to print a calendar of the current month but starting from today's date in python. Is there any way I can do this? Only thing I thought to try was : import calendar y = int(input("Input...   3. Use Python turtle to plot a function. import turtle as t def line(x1,y1,x2,y2): t.up() t.goto(x1,y1) t.down() t.goto(x2,y2) return line(0,300,0,0) line(0,0,300,0) t.goto(0,0) t.shape("turtle") t.color("red") for x in range(0, 151): y = pow(x, 2) + 1 t.goto(x, y * 0.01) t.done() Result:   4. Replace Python list of blank elements with a specific value (list comprehension) z_list = ['oriel', 'indifference', '', 'hypomania', '', 'my'] z_list = ['xxx' if x == '' else x for x in z_list] print(z_list)   5. The prime numbers from 1 to 100 num=0 while num <= 100: cnt = 0 i = 1 while i<=num: if num % i == 0: cnt += 1 i += 1 if cnt == 2: print(num, end=" ") num += 1 Result: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97  
python · May 22, 2023, 2:42 a.m.
How to move multiple turtles at the same time?
from turtle import Turtle, Screen screen = Screen() screen.bgcolor("lightgreen") turtle1 = Turtle(shape='turtle') turtle1.color('red') turtle1.speed("slow") # = 3 turtle1.penup() turtle2 = Turtle(shape='arrow') turtle2.color('blue') turtle2.speed(4) # "slow" (3) < 4 < "normal" (6) turtle2.penup() # user input function perimeter = screen.numinput("Track Perimeter", "Please enter the perimeter:", default=2000, minval=500, maxval=3000) def full_track_crawl(turtle, shortside, longside): speed = turtle.speed() turtle.pendown() for j in range (2): for i in range(0, int(shortside), speed): turtle.forward(speed) yield(0) turtle.left(90) for i in range(0, int(longside), speed): turtle.forward(speed) yield(0) turtle.left(90) turtle.penup() # set the track def drawTrack(perimeter, ratio): shortside = (perimeter / 2.0) / (ratio + 1) longside = ratio * shortside screen.setup(shortside * 2 + 60, longside + 40) turtle1.setposition(-shortside - 10, -longside / 2) turtle2.setposition(10, -longside / 2) generator1 = full_track_crawl(turtle1, shortside, longside) generator2 = full_track_crawl(turtle2, shortside, longside) while (next(generator1, 1) + next(generator2, 1) < 2): pass drawTrack(perimeter, 2) screen.exitonclick()   Result:   Ref. How to move multiple turtles at the same time? I have an assignment which is asked to set two turtles in a race track (same size but separate track). I am able to make them move, but the second one moves only when the first one moved a half of ...  
python · May 21, 2023, 9:56 p.m.
A simple Rock-Paper-Scissors Game written in Python using turtle graphics
발로 만든 게임.ㅋㅋ import turtle as t import random as r import tkinter as tk from tkinter import messagebox def nemo(w, h, c): t.fillcolor(c) t.begin_fill() t.fd(w) t.rt(90) t.fd(h) t.rt(90) t.fd(w) t.rt(90) t.fd(h) t.end_fill() def button(x, y, b_c, msg): t.pu() t.goto(x, y) t.seth(0) nemo(b_w, b_h, b_c) t.goto(x + b_w/2, y - b_h) t.pencolor('white') t.write(msg, align = 'center', font=("Arial", 30, "normal")) b_w = 200; b_h = 60 rock_x = 300; rock_y = 200 scissors_x = 300; scissors_y = 300 paper_x = 300; paper_y = 100 q_x = 300; q_y = -200 c_x = -500; c_y = 300; p_x = -100; p_y = 300 t.speed(500) win = t.Screen() win.setup(1200, 800) button(scissors_x, scissors_y, 'blue', 'Scissors') button(rock_x, rock_y, 'blue', 'Rock') button(paper_x, paper_y, 'blue', 'Paper') button(q_x, q_y, 'black', 'QUIT') button(c_x, c_y, 'red', 'Computer') button(p_x, p_y, 'green', 'Player') t.addshape('imgs/scissors.gif') t.addshape('imgs/rock.gif') t.addshape('imgs/paper.gif') t.title("ORIEL") com = t.Turtle('imgs/paper.gif') player = t.Turtle('imgs/paper.gif') com.pu(); player.pu() com.goto(-400, 0); player.goto(0, 0) t.pu() t.goto(999,999) pw = 0; p = 2 cw = 0; c = 2 def game(c, p): global cw global pw if p == 0: if c == 0: com.shape('imgs/scissors.gif') elif c == 1: com.shape('imgs/rock.gif') cw += 1 else: com.shape('imgs/paper.gif') pw += 1 elif p == 1: if c == 0: com.shape('imgs/scissors.gif') pw += 1 elif c == 1: com.shape('imgs/rock.gif') else: com.shape('imgs/paper.gif') cw += 1 elif p == 2: if c == 0: com.shape('imgs/scissors.gif') cw += 1 elif c == 1: com.shape('imgs/rock.gif') pw += 1 else: com.shape('imgs/paper.gif') if pw == 2 or cw == 2: if pw == 2: print("I won the game. {}:{}".format(pw, cw)) elif cw == 2: print("I lost the game. {}:{}".format(pw, cw)) msg_box = tk.messagebox.askquestion('ORIEL', 'Do you want to continue?', icon='info') if msg_box == 'yes': pw=0; cw=0 else: win.bye() def check(x, y): if(x >= rock_x and x <= rock_x+b_w and y <= rock_y and y >= rock_y-b_h): p = 1 player.shape('imgs/rock.gif') c = r.randint(0, 2) game(c, p) elif(x >= scissors_x and x <= scissors_x+b_w and y <= scissors_y and y >= scissors_y-b_h): p = 0 player.shape('imgs/scissors.gif') c = r.randint(0, 2) game(c, p) elif(x >= paper_x and x <= paper_x+b_w and y <= paper_y and y >= paper_y-b_h): p = 2 player.shape('imgs/paper.gif') c = r.randint(0, 2) game(c, p) elif(x >= q_x and x <= q_x+b_w and y <= q_y and y >= q_y-b_h): win.bye() else: t.goto(999,999) win.onclick(check) t.done()    
python · May 15, 2023, 8:23 p.m.
python game
Star Patterns in Python
1. * ** *** **** ***** **** *** ** * i=1 while i <=4: print("*" * i) i+=1 i = 5 while i > 0: print("*" * i) i -= 1 # or i = 1 j = 6 while i < j * 2 - 1: if i < j : print('*' * i) else: print('*' * (j - i + j - 2)) i += 1 2. * ** *** **** ***** i = 0 while(i < 5): i += 1 print('*' * i) 3. ***** **** *** ** * for x in range(5, 0, -1): for y in range(x): print("*", end="") print() 4. * ** *** **** ***** ***** **** *** ** * spaces = 5 for x in range(5): for y in range(spaces-1): print(" ", end="") for z in range(0, x + 1): print("*", end="") print() spaces -= 1 spaces = 0 for x in range(5,0,-1): for y in range(spaces): print(" ", end="") for z in range(0,x): print("*", end="") print() spaces+=1 5. * *** ***** ******* ********* ******* ***** *** * rows = 5 k = 0 for i in range(1, rows + 1): for j in range (1, (rows - i) + 1): print(end = " ") while k != (2 * i - 1): print("*", end = "") k = k + 1 k = 0 print() k = 2 m = 1 for i in range(1, rows): for j in range (1, k): print(end = " ") k = k + 1 while m <= (2 * (rows - i) - 1): print("*", end = "") m = m + 1 m = 1 print()  
python · May 9, 2023, 7:33 a.m.
A simple hangman game written in Python using turtle graphics
파이썬 터틀을 이용한 간단한 행맨게임   Result :   Code : import random import turtle screen = turtle.Screen() at = turtle.Turtle() word_list = ["테스트", "oriel", "PHENOMENA"] def get_word(): word = random.choice(word_list) return word.upper() def play(word): at.reset() at.pencolor('black') at.pensize(10) at.pu() at.goto(-120, 20) at.pd() word_completion = "_" * len(word) guessed = False guessed_letters = [] guessed_words = [] tries = 6 exec(display_hangman(tries)) print(word_completion) print("\n") while not guessed and tries > 0: guess = screen.textinput("Input", "한 글자만 입력해주세요 : ") if guess is None: break guess = guess.upper() if len(guess) == 1 and guess.isalpha(): if guess in guessed_letters: print("그 글자는 사용했던 글자입니다. 다른 글자를 입력해주세요 : ") elif guess not in word: print(guess, "틀렸습니다.") tries -= 1 exec(display_hangman(tries)) guessed_letters.append(guess) else: print("축하합니다.", guess, "맞는 글자입니다!") guessed_letters.append(guess) word_as_list = list(word_completion) indices = [i for i, letter in enumerate(word) if letter == guess] for index in indices: word_as_list[index] = guess word_completion = "".join(word_as_list) if "_" not in word_completion: guessed = True elif len(guess) == len(word) and guess.isalpha(): if guess in guessed_words: print("", guess) elif guess != word: print(guess, "틀렸습니다.") tries -= 1 exec(display_hangman(tries)) guessed_words.append(guess) else: guessed = True word_completion = word else: print("졌습니다.") exec(display_hangman(tries)) print(word_completion) print("\n") if guessed: print("축하합니다! 게임에서 승리하셨습니다.") else: print("당신은 기회를 다 쓰셨습니다. 단어는 " + word + ". 다음 기회에!") turtle.title("PHENOMENA.COM") turtle.addshape('분필.gif') turtle.shape('분필.gif') turtle.bgpic('칠판.gif') turtle.pu() turtle.goto(-120, 100) turtle.pencolor('black') turtle.pensize(10) turtle.pd() turtle.fd(50) turtle.fd(100) turtle.fd(350) turtle.penup() turtle.goto(-150, -205) turtle.pd() turtle.right(90) turtle.fd(130) turtle.pu() turtle.goto(-120, 100) turtle.pd() def display_hangman(tries): stages = [ # final state: ''' at.pu() at.goto(-120,-100) at.pd() at.fd(75) ''', # head, torso, both arms, and one leg ''' at.pu() at.goto(-120,-100) at.pd() at.rt(90) at.fd(75) ''', # head, torso, and both arms ''' at.pu() at.goto(-120,-20) at.pd() at.fd(70) ''', # head, torso, and one arm ''' at.pu() at.goto(-120,-20) at.pd() at.rt(45) at.fd(70) ''', # head and torso ''' at.pu() at.goto(-120,-100) at.pd() at.fd(115) ''', # head ''' ''', '' ] return stages[tries] def main(): word = get_word() play(word) while screen.textinput("Next Game", "Play Again? (Y/N) ") in ["y", "Y"]: word = get_word() play(word) if __name__ == "__main__": main()  
python · May 8, 2023, 9:51 p.m.
python hangman
Realtime chat app using Django Daphne Nginx Redis
Create your virtual environment. download package in this order Django==3.0.8 djangorestframework==3.11.0 websocket-client==0.57.0 redis==3.5.3 asgiref==3.2.10 channels-redis==2.4.2 channels==3.0.1 Then create a Django project named ChatApp. django-admin startproject ChatApp After installing channels, add channels to your installed apps. INSTALLED_APPS = [ 'chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # add django channels 'channels' , ] Set the ASGI application to your default ASGI file in the project. ASGI_APPLICATION = 'ChatApp.asgi.application' Create a new app that will have all the chat functionality. python startapp chat And add your app to the installed apps in And add chat/ from django.urls import path, include from chat import views as chat_views urlpatterns = [ path("chat", chat_views.chatPage, name="chat-page"), ] And add chat/ from django.urls import re_path from chat.consumers import ChatConsumer # Here, "ws" is routing to the URL ChatConsumer which # will handle the chat functionality. websocket_urlpatterns = [ re_path(r'ws$', ChatConsumer.as_asgi()), ] And add chat/ import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.roomGroupName = "group_chat_gfg" await self.channel_layer.group_add( self.roomGroupName, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.roomGroupName, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] await self.channel_layer.group_send( self.roomGroupName, { "type": "sendMessage", "message": message, "username": username, }) async def sendMessage(self, event): message = event["message"] username = event["username"] await self.send(text_data=json.dumps({"message": message, "username": username})) And add ChatApp/ * Has anyone had problem like this? Traceback (most recent call last): File "/path/to/my/env/bin/daphne", line 11, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/path/to/my/env/lib/python3.6/site-packages/daphne/", line 161, in entrypoint cls().run(sys.argv[1:]) File "/path/to/my/env/lib/python3.6/site-packages/daphne/", line 222, in run application = import_by_path(args.application) File "/path/to/my/env/lib/python3.6/site-packages/daphne/", line 12, in import_by_path target = importlib.import_module(module_path) File "/path/to/my/env/lib/python3.6/importlib/", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./my_project/", line 5, in <module> application = get_default_application() File "/path/to/my/env/lib/python3.6/site-packages/channels/", line 33, in get_default_application module = importlib.import_module(path) File "/path/to/my/env/lib/python3.6/importlib/", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./my_project/", line 4, in <module> from channels.auth import AuthMiddlewareStack File "/path/to/my/env/lib/python3.6/site-packages/channels/", line 12, in <module> from django.contrib.auth.models import AnonymousUser File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/", line 47, in <module> class AbstractBaseUser(models.Model): File "/path/to/my/env/lib/python3.6/site-packages/django/db/models/", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/path/to/my/env/lib/python3.6/site-packages/django/apps/", line 244, in get_containing_app_config self.check_apps_ready() File "/path/to/my/env/lib/python3.6/site-packages/django/apps/", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Then visit this page. Django apps aren't loaded yet when using asgi I'm tring to run my django project with usage of asgi instead of wsgi. I have set up my and as follows: from django.conf.urls import url from channels.routing import   ChatApp/ CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } }   Using Redis: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('', 6379)] }, }, }   * Deploying Django Channels: how to keep Daphne running after exiting shell on web server Deploying Django Channels: how to keep Daphne running after exiting shell on web server As practice, I'm trying to deploy Andrew Godwin's multichat example with Django Channels 2.1.1 on DigitalOcean Ubuntu 16.04.4. However, I don't know how to exit the Ubuntu server without Channels' ...   Nginx 1. Windows location @django { proxy_pass; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 600s; # this next line adds the Host header so that apache knows which vHost to serve # the $host variable is automatically set to the hostname Nginx is responding to proxy_set_header Host $host; #Websocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } 2. Linux with Daphne Make service-name.service [Unit] Description=Indifference Daphne Service [Service] Type=simple User=indifference WorkingDirectory=/home/indifference/path/to/indifference ExecStart=/home/indifference/path/to/bin/daphne -p 3333 indifference.asgi:application access-log=/data/logs/indifference/daphne/access.log [Install] chmod 755 service-name.service systemctl daemon-reload systemctl enable service-name.service systemctl start service-name.service Update nginx.conf  upstream channels-indifference-backend { server localhost:3333; } ... location /ws { proxy_pass http://channels-indifference-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; }   Windows Django - dev Create a folder called config config/ make sure that in and you import everything from like this: from .commonsettings import * sample INSTALLED_APPS = [ ... # 'channels', ... ] ASGI_APPLICATION = None then if you want to run the settings: python runserver In order to run your asgi application, simply point Daphne to your ASGI application, and optionally set a bind address and port (defaults to localhost, port 8000): daphne -b -p 9001 myproject.asgi:application Nginx WS config is the same with 2. Linux with Daphne * Use ASGI to deploy Django, StreamingHttpResponse cannot be accessed. Async support for StreamingHttpResponse was only added in Django 4.2.   You can check the program with this:   Ref. Realtime chat app using Django - GeeksforGeeks A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. Django Channel Custom Authentication Middleware __call__() missing 2 required positional arguments: 'receive' and 'send' I am writing a custom authentication middleware for django channels class TokenAuthMiddleware: def __init__(self, inner): # Store the ASGI application we were passed self.inner = Configuring ASGI Django Application using Daphne and Nginx Server Adding Daphne to preexisting project. Channels cannot be used with StreamingHttpResponse So you’re saying that this exact code works if you run it under a wsgi container?  
python · March 2, 2023, 6:55 a.m.
django daphne nginx redis
How to include only needed modules in pyinstaller?
For this you need to create a separate environment, because currently you are reading all the modules you have installed on your computer. To create environment run commands 1 - if you don't have one, create a requirements.txt file that holds all packages that you are using, you could create one with: pip freeze > requirements.txt 2 - create env folder: python -m venv projectName 3 - activate the environment: source projectName/bin/activate 4 - install them: pip install -r requirements.txt alternatively if you know you are using only wxpython you could just pip install wxpython 5 - then finally you can run pyinstaller on your main script with the --path arg as explained in this answer: pyinstaller --paths projectName/lib/python3.7/site-packages   How to include only needed modules in pyinstaller? I'm using pyinstaller to generate an .exe file for my single python file, but the size is more than 30MB and the startup is very slow. From what I have gathered is that pyinstaller by default bundl...  
python · Feb. 23, 2023, 8:36 p.m.
Django migrate gets error "table already exists"
1. Remove all migration files in <appname>/migrations 2. Remove all data in django_migrations table where app = <appname> 3.  python makemigrations <appname> 4.  python migrate --fake <appname> 5. If you have a field to alter, then alter the field <field> on <appname> and then again python makemigrations <appname> 6. python migrate <appname> Child's play.   0003이 실제로 적용된 가장 최근의 마이그레이션이라 가정할 때에는? --fake를 이용하여 현재 상태는 0003이다 라고 장고가 인식하게끔 해주어야 한다. python migrate --fake <appname> 0003 그 후 평소 하던대로 진행.   django 1.7 migrate gets error "table already exists" I am trying to apply a migration but am getting the error: django.db.utils.OperationalError: (1050, "Table 'customers_customer' already exists") I get this by issuing the following command: ... How to redo a migration on django 1.8 after using --fake Something went wrong on my migrations, I added a new datetimefield to a model then I used makemigrations and migrate. python makemigrations python migrate But after this the m...
python · Jan. 12, 2023, 9:59 p.m.
django migration
  • 1 (current)
  • 2