Collage

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

python

1. Install Geckodriver Go to the geckodriver releases page. Find the latest version of the driver for your platform and download it. For example: wget https://github.com/mozilla/geckodriver/releases/download/v0.35.0/geckodriver-v0.35.0-linux64.tar.gz Extract the file with: tar -xvzf geckodriver* Make it executable: chmod +x geckodriver Add the driver to your PATH so other tools can find it: sudo mv geckodriver /usr/local/bin/   2. Install Selenium pip install selenium   3. Sample code from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver import FirefoxOptions class TestView(View): def post(self, request, *args, **kwargs): query = kwargs["query"] url = f"https://www.vought.com/search?q={query}" opts = FirefoxOptions() opts.add_argument("--headless") browser = webdriver.Firefox(options=opts, executable_path=settings.SELENIUM_PATH) browser.get(url) html = browser.page_source sor = BeautifulSoup(html, "html.parser") target = sor.find("div", {"id": "x"}) text = target.text browser.quit() return JsonResponse({"result": text}, json_dumps_params={'ensure_ascii': False}, safe=False , content_type=u"application/json; charset=utf-8") * SELENIUM_PATH Examples Linux : /usr/local/bin/geckodriver Windows : B:\path\to\geckodriver-v0.30.0-win64\geckodriver.exe   Ref. How to install geckodriver in Ubuntu? I use Selenium in Python, I tried to run the webdriver function: default_browser = webdriver.Firefox() This Exception: WebDriverException: Message: 'geckodriver' executable needs to be in PATH. https://askubuntu.com/questions/870530/how-to-install-geckodriver-in-ubuntu Selenium and web driver setup for ubuntu In this article, I am going to explain selenium and web driver setup for ubuntu. https://medium.com/featurepreneur/selenium-and-web-driver-setup-for-ubuntu-4c41cb61cb6f
John Doe · Oct. 13, 2024, 3:36 a.m.
selenium BeautifulSoup
Error File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in apply_converters 779. value = converter(value, expression, self.connection, self.query.context) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/functions/datetime.py" in convert_value 181. "Database returned an invalid datetime value. " ValueError: Database returned an invalid datetime value. Are time zone definitions for your database installed?   Solution 1. Linux contact@me:~$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql contact@me:~$ mysql -u root -p -e "flush tables;" mysql 2. Windows 1) Download posix timezone sql from https://dev.mysql.com/downloads/timezones.html 2) Do not move anything, just open this sql file in MySQL Workbench and add USE mysql; to the first line. 3) Run this file and that's it   * How to run SQL script in MySQL? 1. If you’re at the MySQL command line mysql> you have to declare the SQL file as source. mysql> source \home\user\Desktop\test.sql; 2. CMD   Ref. Django Mysql Database returned an invalid datetime value I have a Django app. I am using MySql server running in docker container as a database. After just moved to a custom User model. Now i am getting those errors: Environment: Request Method: GET Req... https://stackoverflow.com/questions/40792628/django-mysql-database-returned-an-invalid-datetime-value Database returned an invalid datetime value. Are time zone definitions for your database installed? i tried to TruncDay in django to turn date into day format , i use mysql version 8.0 with windows 10 this my settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True date = m... https://stackoverflow.com/questions/62581502/database-returned-an-invalid-datetime-value-are-time-zone-definitions-for-your [DB] MySQL SQL파일 실행 및 백업 ■ SQL파일 실행 1. 프롬프트(cmd) 환경 예시) mysql -u(유저명) -p < sql파일명.sql mysql -uroot -p < testFile.sql 1) testFile.sql 내용 확인 2) 프롬프트(cmd)에서 실행 2. MySQL 접속 환경 예시) source sql파일명.sql source C:\MySQL\testFile.sql ■ SQL파일로 DataBase 백업 ※ 프롬프트(cmd) 환경 예시) mysqldump -u(유저명) https://hyunmin1906.tistory.com/103   * MariaDB에서 root 암호 인증 방식이 먹히지 않는 이유(feat. unix_socket) [B급 프로그래머] MariaDB에서 root 암호 인증 방식이 먹히지 않는 이유(feat. unix_socket) "컴퓨터와 책에 대한 블로그입니다." https://jhrogue.blogspot.com/2020/02/b-mariadb-root-feat-unixsocket.html MariaDB; 인증(Authentication) 문제. – 바깥 세상으로.. (As a kite by then) Skip to content 바깥 세상으로.. (As a kite by then) Search for: × Menu 첫머리 이곳은? 以前 記錄 記憶 (egloos) 주저리주저리 Prince & New Power Generation – Diamonds & Pearls 갑자기, Prince. Tears for Fears: The Tipping Point Pat Metheny: Road to the Sun 김태은/오경희/정민아 : 산조的 감각 Pat Meth https://www.nemonein.xyz/2019/07/2254/
John Doe · June 10, 2024, 7:22 p.m.
django SQL
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='oriel.com' , 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 = "https://nd-123-456-789.p2pify.com/901c7d18b72538fd3324248e1234" 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(“https://google.com”).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.   https://support.chainstack.com/hc/en-us/articles/9117198436249-Common-SSL-Issues-on-Python-and-How-to-Fix-it 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.... https://stackoverflow.com/questions/51925384/unable-to-get-local-issuer-certificate-when-using-requests 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 = 'https://10.0.0.39:4455/api/cars' response = requests.get(url, verify= https://stackoverflow.com/questions/75913891/httpsconnectionpool-max-retries-exceeded-with-url-caused-by-sslerror CERTIFICATE_VERIFY_FAILED error Python Django error: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)&gt; Exception Location: /usr/lib/python3.8/u... https://askubuntu.com/questions/1401379/certificate-verify-failed-error 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... https://stackoverflow.com/questions/70977935/why-do-i-receive-unable-to-get-local-issuer-certificate-ssl-c997 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('http://facebook.com') I receive back the https://stackoverflow.com/questions/72188582/sslerror-max-retries-exceeded-with-url-error-how-to-fix-this
John Doe · Aug. 29, 2023, 8:15 p.m.
ssl python
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 settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myusername@gmail.com' https://stackoverflow.com/questions/20325729/django-reset-password-not-sending-email   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 │ │ └── setup.py │   ├── app2 │ │ ├── app2 │ │ └── setup.py ├── my_django_project │   ├── appA │   ├── appB │  ... https://stackoverflow.com/questions/30426823/how-do-i-run-makemessages-so-it-includes-some-apps-that-are-outside-the-django-p   3) requirements.txt 를 통한 패키지 종속성 관리 현재 환경에서 설치한 패키지 확인 pip freeze 설치한 패키지 목록을 파일에 담기 pip freeze > requirements.txt 패키지 설치 pip install -r requirements.txt ssl 오류가 발생할 경우에는 pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements.txt   4) django management 시스템 안에서 내 명령어 만들고 사용하기 app들을 import하여 만든 코드를 서버시작없이 콘솔에서 테스트 또는 실행하고 싶을 때 유용함. 그냥 Run 해버리면 import된 모듈을 찾을 수 없다고 나온다. shell 명령을 쓰지않아도 되어서 편하다 1. 폴더구조를 아래와같이 만들어야 한다 $ tree CallCenter ├── admin.py ├── apps.py ├── __init__.py ├── management │ └── commands 2. 이제 commands 폴더 안에 내가 쓰고자 하는 명령어의 이름으로 python 파일을 작정한다 여기서는 make_call.py CallCenter/management/commands/make_call.py from twilio.rest import Client from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse from CallCenter.models import Campaign from django.core.management 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 manage.py 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 views.py. I'm getting an error: Traceback (most recent call last): File "CallCenter\make_call.py", line ... https://stackoverflow.com/questions/58286858/how-to-run-a-python-script-in-django   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... https://github.com/pennersr/django-allauth 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. https://github.com/python-social-auth/social-app-django 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 twitter.com. You can see a list of supported browsers in our Help Center. Help Center Term https://developer.twitter.com/en/portal/petition/essential/basic-info 네이버: 애플리케이션 - NAVER Developers 애플리케이션 - NAVER Developers   https://developers.naver.com/apps/#/list 네이버로 연동된 app목록은 여기서 확인가능 Apps : NAVER Account 네이버 네이버에 로그인 하고 나를 위한 다양한 서비스를 이용해 보세요 https://nid.naver.com/internalToken/view/tokenList/pc/en 구글: https://console.developers.google.com/apis/dashboard 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 https://console.developers.google.com/apis/dashboard 이중 가장 까다로웠던건 네이버연동. 첨에 신청했다가 어떤목적 사이트인지 기술안했다고 반려당하고 가입시 선택사항으로 이름을 넣어놨는데 사용목적이 안나왔다고 반려당하고 선택사항삭제하고 별명을 필수로 넣었는데 어디에 쓰이는지 알수없다고해서 캡쳐후 재신청하고 검수 승인까지 좀 걸렸었다.
John Doe · June 27, 2023, 10:27 a.m.
django
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 selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui 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 = "https://oriel.com" 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 (web.whatsapp.com) 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 https://stackoverflow.com/questions/45651879/using-selenium-how-to-keep-logged-in-after-closing-driver-in-python 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 https://groups.google.com/g/selenium-users/c/CL8kdxhgdj0
John Doe · June 2, 2023, 3:23 a.m.
selenium
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(&quot;Input... https://stackoverflow.com/questions/62861105/print-a-calendar-starting-from-todays-date   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
John Doe · May 22, 2023, 2:42 a.m.
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 ... https://stackoverflow.com/questions/40050438/how-to-move-multiple-turtles-at-the-same-time
John Doe · May 21, 2023, 9:56 p.m.
발로 만든 게임.ㅋㅋ 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()
John Doe · May 15, 2023, 8:23 p.m.
python game
파이썬 터틀을 이용한 간단한 행맨게임   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.lt(90) turtle.fd(50) turtle.lt(90) turtle.fd(100) turtle.lt(90) 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.lt(90) 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.lt(90) 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.lt(90) at.fd(115) ''', # head ''' at.circle(40) ''', '' ] 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()
John Doe · May 8, 2023, 9:51 p.m.
python hangman
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 manage.py startapp chat And add your app to the installed apps in settings.py. And add chat/urls.py 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/routing.py 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/consumers.py 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/asgi.py * 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/cli.py", line 161, in entrypoint cls().run(sys.argv[1:]) File "/path/to/my/env/lib/python3.6/site-packages/daphne/cli.py", line 222, in run application = import_by_path(args.application) File "/path/to/my/env/lib/python3.6/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/path/to/my/env/lib/python3.6/importlib/__init__.py", 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/asgi.py", line 5, in <module> application = get_default_application() File "/path/to/my/env/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/path/to/my/env/lib/python3.6/importlib/__init__.py", 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/routing.py", line 4, in <module> from channels.auth import AuthMiddlewareStack File "/path/to/my/env/lib/python3.6/site-packages/channels/auth.py", line 12, in <module> from django.contrib.auth.models import AnonymousUser File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/models.py", 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/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/path/to/my/env/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", 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 routing.py and asgi.py as follows: routing.py from django.conf.urls import url from channels.routing import https://stackoverflow.com/questions/53683806/django-apps-arent-loaded-yet-when-using-asgi   ChatApp/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } }   Using Redis: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 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' ... https://stackoverflow.com/questions/50192967/deploying-django-channels-how-to-keep-daphne-running-after-exiting-shell-on-web   Nginx 1. Windows location @django { proxy_pass http://127.0.0.1:1234; 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 After=network.target [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] WantedBy=multi-user.target 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; } Still not working? Just restart it. systemctl stop service-name.service systemctl start service-name.service systemctl status service-name.service   Windows Django - dev Create a folder called config config/ commonsettings.py dev.py prod.py make sure that in dev.py and prod.py you import everything from commonsettings.py like this: from .commonsettings import * dev.py sample INSTALLED_APPS = [ ... # 'channels', ... ] ASGI_APPLICATION = None then if you want to run the dev.py settings: python manage.py runserver --settings=config.dev 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 0.0.0.0 -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: https://www.phenomena.com/chat   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. https://www.geeksforgeeks.org/realtime-chat-app-using-django/ 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 = https://stackoverflow.com/questions/64625473/django-channel-custom-authentication-middleware-call-missing-2-required-po Configuring ASGI Django Application using Daphne and Nginx Server Adding Daphne to preexisting project. https://ritiktaneja.medium.com/configuring-asgi-django-application-using-daphne-and-nginx-server-59a90456fe17 Channels cannot be used with StreamingHttpResponse So you’re saying that this exact code works if you run it under a wsgi container? https://forum.djangoproject.com/t/channels-cannot-be-used-with-streaminghttpresponse/10105/4
John Doe · March 2, 2023, 6:55 a.m.
django daphne nginx redis
  • 1 (current)
  • 2