diff --git a/coupang_commission.py b/coupang_commission.py new file mode 100644 index 0000000..db8318d --- /dev/null +++ b/coupang_commission.py @@ -0,0 +1,52 @@ +import hmac +import hashlib +import requests +import json +from time import gmtime, strftime +import smssend +from datetime import date, timedelta + +yesterday = date.today() - timedelta(1) +DATE = yesterday.strftime('%Y%m%d') +REQUEST_METHOD = "GET" +DOMAIN = "https://api-gateway.coupang.com" +URL = "/v2/providers/affiliate_open_api/apis/openapi/v1/reports/commission?startDate="+DATE+"&endDate="+DATE+"&page=0" + +# Replace with your own ACCESS_KEY and SECRET_KEY +ACCESS_KEY = "" +SECRET_KEY = "" + +def generateHmac(method, url, secretKey, accessKey): + path, *query = url.split("?") + datetimeGMT = strftime('%y%m%d', gmtime()) + 'T' + strftime('%H%M%S', gmtime()) + 'Z' + message = datetimeGMT + method + path + (query[0] if query else "") + + signature = hmac.new(bytes(secretKey, "utf-8"), + message.encode("utf-8"), + hashlib.sha256).hexdigest() + + return "CEA algorithm=HmacSHA256, access-key={}, signed-date={}, signature={}".format(accessKey, datetimeGMT, signature) + + +authorization = generateHmac(REQUEST_METHOD, URL, SECRET_KEY, ACCESS_KEY) +url = "{}{}".format(DOMAIN, URL) +response = requests.request(method=REQUEST_METHOD, url=url, + headers={ + "Authorization": authorization, + "Content-Type": "application/json" + }, + + ) + +data = response.json() + +for row in data['data']: + uid = "" + upw = "" + subject = "쿠팡파트너스" + content = "쿠팡파트너스 \n날짜: {} \n커미션: {}원".format(row['date'], row['commission']) + hpno = "" + callback = "" + + jphone = smssend.JmunjaPhone(uid, upw) + presult = jphone.send(subject, content, hpno) diff --git a/fake_data_make.py b/fake_data_make.py new file mode 100644 index 0000000..f757694 --- /dev/null +++ b/fake_data_make.py @@ -0,0 +1,11 @@ +from faker import Faker +import csv + +fake = Faker("ko_KR") + +with open("fake_data.csv", "w", encoding="utf-8", newline='') as f: + wr = csv.writer(f) + for _ in range(10000): + profile = fake.profile() + print(profile['name'], profile['sex'], profile['ssn'], profile['mail']) + wr.writerow([profile['name'], profile['sex'], profile['ssn'], profile['mail']]) diff --git a/fake_data_make_dbsave.py b/fake_data_make_dbsave.py new file mode 100644 index 0000000..f9af949 --- /dev/null +++ b/fake_data_make_dbsave.py @@ -0,0 +1,31 @@ +""" +CREATE TABLE `test`.`user` ( + `no` INT NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NULL, + `sex` VARCHAR(1) NULL, + `ssn` VARCHAR(14) NULL, + `email` VARCHAR(45) NULL, + PRIMARY KEY (`no`)); +""" + +from faker import Faker +import pymysql + +conn = pymysql.connect(host="localhost", user="root", password="1234", db="test", charset="utf8") +curs = conn.cursor() + +fake = Faker("ko_KR") + +with open("fake_data.csv", "w", encoding="utf-8", newline='') as f: + + for _ in range(1000): + profile = fake.profile() + print(profile['name'], profile['sex'], profile['ssn'], profile['mail']) + try: + sql = "insert into user (name, sex, ssn, email)" \ + "values (%s, %s, %s, %s)" + curs.execute(sql, (profile['name'], profile['sex'], profile['ssn'], profile['mail'])) + except: + pass +conn.commit() +conn.close() diff --git a/firebase_messaing_v1.py b/firebase_messaing_v1.py new file mode 100644 index 0000000..2925dd6 --- /dev/null +++ b/firebase_messaing_v1.py @@ -0,0 +1,19 @@ +import firebase_admin +from firebase_admin import credentials +from firebase_admin import messaging + +cred_path = "firebase-adminsdk-myproject.json" +cred = credentials.Certificate(cred_path) +firebase_admin.initialize_app(cred) + +registration_token = 'user_token' + +message = messaging.Message( + notification=messaging.Notification( + title='test', + body='python push test' + ), + token=registration_token, +) +response = messaging.send(message) +print('Successfully sent message:', response) diff --git a/fss_dic_new.py b/fss_dic_new.py new file mode 100644 index 0000000..8f27cc1 --- /dev/null +++ b/fss_dic_new.py @@ -0,0 +1,55 @@ +import requests +from bs4 import BeautifulSoup +import re +import sqlite3 + +fdic = {} +list_a = [] +list_b = [] + +for page in range(1, 55): + url = "https://fine.fss.or.kr/fine/fnctip/fncDicary/list.do?menuNo=900021&pageIndex="+str(page)+"&src=&kind=&searchCnd=1&searchStr=" + print(url) + + response = requests.get(url) + + if response.status_code == 200: + html = response.text + soup = BeautifulSoup(html, 'html.parser') + + ul = soup.select_one('#content > div.bd-list.result-list') + sub = ul.select('dl > dt') + con = ul.select('dl > dd') + + for i in sub: + tmp = i.get_text().strip() + tmp = tmp.replace("\r\n", "").replace("\t", "") + tmp = re.sub('^[0-9]+.', '', tmp) + list_a.append(tmp) + # print(tmp) + + for i in con: + tmp = i.get_text().strip() + list_b.append(tmp) + # print(tmp) + + + else: + print(response.status_code) + +for i in range(len(list_a)): + fdic[i] = [list_a[i], list_b[i]] + +conn = sqlite3.connect("fdic.db") +cur = conn.cursor() +conn.execute("create table fss_dic(id integer, name text, content text)") + +for i in fdic: + name = fdic[i][0] + content = fdic[i][1] + + sql = "insert into fss_dic values (?, ?, ?)" + cur.execute(sql, (i, name, content)) + +conn.commit() +conn.close() \ No newline at end of file diff --git a/hanabank_exchange_rate.xlsx b/hanabank_exchange_rate.xlsx new file mode 100644 index 0000000..7150cff Binary files /dev/null and b/hanabank_exchange_rate.xlsx differ diff --git a/hanabank_exchange_rate_crawling.ipynb b/hanabank_exchange_rate_crawling.ipynb new file mode 100644 index 0000000..464204c --- /dev/null +++ b/hanabank_exchange_rate_crawling.ipynb @@ -0,0 +1,279 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 22, + "id": "bdff5bc5", + "metadata": {}, + "outputs": [], + "source": [ + "#!pip install selenium==4.1.5\n", + "#!pip install webdriver_manager\n", + "\n", + "import selenium\n", + "from selenium import webdriver\n", + "from selenium.webdriver.chrome.service import Service # chromedriver 자동설치\n", + "from webdriver_manager.chrome import ChromeDriverManager #chromedriver 자동설치\n", + "from selenium.webdriver.common.by import By\n", + "from selenium.webdriver.support.ui import WebDriverWait\n", + "from selenium.webdriver.support import expected_conditions as EC\n", + "service = Service(executable_path=ChromeDriverManager().install())\n", + "driver = webdriver.Chrome(service=service)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "4c10ae34", + "metadata": {}, + "outputs": [], + "source": [ + "# 인터넷 열기\n", + "driver = webdriver.Chrome(service=service)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "04c864bc", + "metadata": {}, + "outputs": [], + "source": [ + "#driver.get('https://www.kebhana.com/cont/mall/mall15/mall1501/index.jsp?_menuNo=23100#//HanaBank')\n", + "driver.get('https://www.kebhana.com/cms/rate/wpfxd651_01i_01.do?tmpInqStrDt=2023-03-25&pbldDvCd=3&inqStrDt=20230325&inqKindCd=1')" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "6981574d", + "metadata": {}, + "outputs": [], + "source": [ + "exchange_rate_table = driver.find_elements(By.CLASS_NAME, \"tblBasic\")\n", + "print(exchange_rate_table)" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "34092b5c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "tbody = exchange_rate_table[0].find_element(By.TAG_NAME, \"tbody\")\n", + "print(tbody)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "fb42a702", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]\n" + ] + } + ], + "source": [ + "tr = tbody.find_elements(By.TAG_NAME, \"tr\")\n", + "print(tr)" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "5e2a61a2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "미국 USD 1,300.00\n", + "일본 JPY (100) 994.53\n", + "유로 EUR 1,398.93\n", + "중국 CNY 189.23\n", + "홍콩 HKD 165.61\n", + "태국 THB 38.02\n", + "대만 TWD 42.85\n", + "필리핀 PHP 23.95\n", + "싱가포르 SGD 976.16\n", + "호주 AUD 864.11\n", + "베트남 VND (100) 5.53\n", + "영국 GBP 1,589.77\n", + "캐나다 CAD 946.14\n", + "말레이시아 MYR 293.59\n", + "러시아 RUB 16.82\n", + "남아공화국 ZAR 71.55\n", + "노르웨이 NOK 123.95\n", + "뉴질랜드 NZD 806.13\n", + "덴마크 DKK 187.72\n", + "멕시코 MXN 70.46\n", + "몽골 MNT 0.37\n", + "바레인 BHD 3,447.54\n", + "방글라데시 BDT 12.37\n", + "브라질 BRL 247.48\n", + "브루나이 BND 976.16\n", + "사우디아라비아 SAR 346.06\n", + "스리랑카 LKR 4.04\n", + "스웨덴 SEK 124.68\n", + "스위스 CHF 1,413.73\n", + "아랍에미리트공화국 AED 353.99\n", + "알제리 DZD 9.55\n", + "오만 OMR 3,376.80\n", + "요르단 JOD 1,832.66\n", + "이스라엘 ILS 362.08\n", + "이집트 EGP 42.07\n", + "인도 INR 15.78\n", + "인도네시아 IDR (100) 8.60\n", + "체코 CZK 59.08\n", + "칠레 CLP 1.60\n", + "카자흐스탄 KZT 2.84\n", + "카타르 QAR 357.14\n", + "케냐 KES 9.89\n", + "콜롬비아 COP 0.27\n", + "쿠웨이트 KWD 4,246.01\n", + "탄자니아 TZS 0.56\n", + "터어키 TRY 68.19\n", + "파키스탄 PKR 4.60\n", + "폴란드 PLN 298.40\n", + "헝가리 HUF 3.63\n", + "네팔 NPR 9.85\n", + "마카오 MOP 160.67\n", + "캄보디아 KHR 0.32\n", + "피지 FJD 586.04\n", + "리비아 LYD 273.18\n", + "루마니아 RON 283.81\n", + "미얀마 MMK 0.62\n", + "에티오피아 ETB 24.13\n", + "우즈베키스탄 UZS 0.11\n" + ] + } + ], + "source": [ + "nation = []\n", + "exrate = []\n", + "for item in tr:\n", + " td = item.find_elements(By.TAG_NAME, \"td\")\n", + " print(td[0].text, td[9].text)\n", + " nation.append(td[0].text)\n", + " exrate.append(td[9].text)" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "id": "15194fab", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " 국가 환율\n", + "0 미국 USD 1,300.00\n", + "1 일본 JPY (100) 994.53\n", + "2 유로 EUR 1,398.93\n", + "3 중국 CNY 189.23\n", + "4 홍콩 HKD 165.61\n", + "5 태국 THB 38.02\n", + "6 대만 TWD 42.85\n", + "7 필리핀 PHP 23.95\n", + "8 싱가포르 SGD 976.16\n", + "9 호주 AUD 864.11\n", + "10 베트남 VND (100) 5.53\n", + "11 영국 GBP 1,589.77\n", + "12 캐나다 CAD 946.14\n", + "13 말레이시아 MYR 293.59\n", + "14 러시아 RUB 16.82\n", + "15 남아공화국 ZAR 71.55\n", + "16 노르웨이 NOK 123.95\n", + "17 뉴질랜드 NZD 806.13\n", + "18 덴마크 DKK 187.72\n", + "19 멕시코 MXN 70.46\n", + "20 몽골 MNT 0.37\n", + "21 바레인 BHD 3,447.54\n", + "22 방글라데시 BDT 12.37\n", + "23 브라질 BRL 247.48\n", + "24 브루나이 BND 976.16\n", + "25 사우디아라비아 SAR 346.06\n", + "26 스리랑카 LKR 4.04\n", + "27 스웨덴 SEK 124.68\n", + "28 스위스 CHF 1,413.73\n", + "29 아랍에미리트공화국 AED 353.99\n", + "30 알제리 DZD 9.55\n", + "31 오만 OMR 3,376.80\n", + "32 요르단 JOD 1,832.66\n", + "33 이스라엘 ILS 362.08\n", + "34 이집트 EGP 42.07\n", + "35 인도 INR 15.78\n", + "36 인도네시아 IDR (100) 8.60\n", + "37 체코 CZK 59.08\n", + "38 칠레 CLP 1.60\n", + "39 카자흐스탄 KZT 2.84\n", + "40 카타르 QAR 357.14\n", + "41 케냐 KES 9.89\n", + "42 콜롬비아 COP 0.27\n", + "43 쿠웨이트 KWD 4,246.01\n", + "44 탄자니아 TZS 0.56\n", + "45 터어키 TRY 68.19\n", + "46 파키스탄 PKR 4.60\n", + "47 폴란드 PLN 298.40\n", + "48 헝가리 HUF 3.63\n", + "49 네팔 NPR 9.85\n", + "50 마카오 MOP 160.67\n", + "51 캄보디아 KHR 0.32\n", + "52 피지 FJD 586.04\n", + "53 리비아 LYD 273.18\n", + "54 루마니아 RON 283.81\n", + "55 미얀마 MMK 0.62\n", + "56 에티오피아 ETB 24.13\n", + "57 우즈베키스탄 UZS 0.11\n" + ] + } + ], + "source": [ + "import pandas as pd\n", + "\n", + "df = pd.DataFrame({'국가':nation, '환율':exrate})\n", + "print(df)\n", + "\n", + "df.to_excel(\"hanabank_exchange_rate.xlsx\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/keyboard_hook.py b/keyboard_hook.py new file mode 100644 index 0000000..7027d70 --- /dev/null +++ b/keyboard_hook.py @@ -0,0 +1,49 @@ +import keyboard +import threading +import pyautogui +from time import sleep + + +class Hook(threading.Thread): + def __init__(self): + super(Hook, self).__init__() # 부모 클래스 __init__ 실행 + self.daemon = True # 데몬 쓰레드로 설정 + self.event = False # f4가 눌리면 event 발생 + self.my_xy = [] # 좌표 저장 리스트 + keyboard.unhook_all() # 후킹 초기화 + keyboard.add_hotkey('f4', print, args=['\n종료합니다']) # f4가 눌리면 print 실행 + keyboard.add_hotkey('f2', print, args=['\n좌표값이 추가되었습니다']) # f2가 눌리면 print 실행 + + def run(self): # run 메소드 재정의 + while True: + key = keyboard.read_hotkey(suppress=False) # hotkey를 계속 읽음 + if key == 'f4': # f4 받은 경우 + self.event = True # event 클래스 변수를 True로 설정 + # print("\n", self.my_xy) + + with open(r"config.txt", "w") as f: + for i in self.my_xy: + f.write("{},{}\n".format(i[0], i[1])) + + break # 반복문 탈출 + + elif key == 'f2': + position = pyautogui.position() + self.my_xy.append((position.x, position.y)) + + +def track_pos(): + h = Hook() # 훅 쓰레드 생성 + h.start() # 쓰레드 실행 + print('size:', pyautogui.size()) # 화면 크기 출력 + + while True: # 무한루프 + if h.event == True: # h.event가 True이면(f4 입력받은 경우) 종료 + break + position = pyautogui.position() # 마우스 현재 위치(x, y) 반환 + print(f'\r{position.x:4}, {position.y:4}', end='') + sleep(0.05) + h.join() # 쓰레드 종료까지 대기 + keyboard.unhook_all() # 후킹 해제 + +track_pos() \ No newline at end of file diff --git a/keyboard_hook_230728.py b/keyboard_hook_230728.py new file mode 100644 index 0000000..92cf7c4 --- /dev/null +++ b/keyboard_hook_230728.py @@ -0,0 +1,58 @@ +import keyboard +import threading +import pyautogui +from time import sleep +import os + + +class Hook(threading.Thread): + def __init__(self): + super(Hook, self).__init__() # 부모 클래스 __init__ 실행 + self.daemon = True # 데몬 쓰레드로 설정 + self.event = False # f4가 눌리면 event 발생 + self.my_xy = [] # 좌표 저장 리스트 + keyboard.unhook_all() # 후킹 초기화 + keyboard.add_hotkey('f4', print, args=['\n종료합니다']) # f4가 눌리면 print 실행 + keyboard.add_hotkey('f2', print, args=['\n좌표값이 추가되었습니다']) # f2가 눌리면 print 실행 + + def run(self): # run 메소드 재정의 + while True: + key = keyboard.read_hotkey(suppress=False) # hotkey를 계속 읽음 + if key == 'f4': # f4 받은 경우 + self.event = True # event 클래스 변수를 True로 설정 + # print("\n", self.my_xy) + + with open(r"config.txt", "w") as f: + for i in self.my_xy: + f.write("{},{}\n".format(i[0], i[1])) + + break # 반복문 탈출 + + elif key == 'f2': + position = pyautogui.position() + self.my_xy.append((position.x, position.y)) + + +def track_pos(): + h = Hook() # 훅 쓰레드 생성 + h.start() # 쓰레드 실행 + print('size:', pyautogui.size()) # 화면 크기 출력 + + while True: # 무한루프 + if h.event == True: # h.event가 True이면(f4 입력받은 경우) 종료 + break + position = pyautogui.position() # 마우스 현재 위치(x, y) 반환 + print(f'\r{position.x:4}, {position.y:4}', end='') + sleep(0.05) + h.join() # 쓰레드 종료까지 대기 + keyboard.unhook_all() # 후킹 해제 + + +try: + cur_path = os.path.dirname(os.path.realpath(__file__)) + with open(cur_path+"/memo.txt", "r") as f: + print(f.readline()) +except: + pass + +track_pos() \ No newline at end of file diff --git a/keyboard_hook_230728_run.exe b/keyboard_hook_230728_run.exe new file mode 100644 index 0000000..d9babfe Binary files /dev/null and b/keyboard_hook_230728_run.exe differ diff --git a/muju_gondora_reservation_5s_check.py b/muju_gondora_reservation_5s_check.py new file mode 100644 index 0000000..be5b128 --- /dev/null +++ b/muju_gondora_reservation_5s_check.py @@ -0,0 +1,60 @@ +import requests +from bs4 import BeautifulSoup +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from jmunja import smssend +import time # 추가된 모듈 + + +# 예약 사이트 URL +URL = "https://www.mdysresort.com/gondora/res_gon1.asp?" + + +# 예약 상태 확인 함수 +def check_availability(): + try: + response = requests.get(URL, timeout=5) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "html.parser") + reservation_elements = soup.select("#res_gon1 > div > div.cal_con > div.calendar_box > div:nth-child(4) > ul.sat > li.res") + + for element in reservation_elements: + if "매진" not in element.text: + return True # 예약 가능 상태 발견 + return False # 모든 항목이 매진 상태 + except requests.exceptions.Timeout: + print("Request timed out. Please try again.") + except requests.exceptions.RequestException as e: + print(f"An error occurred: {e}") + + +# SMS 보내기 함수 (제이문자) +def send_sms_notification(): + uid = "" + upw = "" + subject = "곤도라예약" + content = "곤도라 예약이 가능합니다! 지금 바로 사이트를 방문하세요: " + URL, + + jphone = smssend.JmunjaPhone(uid, upw) + result = jphone.send(subject, content, "01012345678") + + if result: + print("SMS 발송 완료") + + +# 메인 함수 +def main(): + while True: + if check_availability(): + print("예약 가능 상태 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + send_sms_notification() + time.sleep(30) + else: + print("모든 예약이 매진 상태입니다.") + pass + time.sleep(5) + +if __name__ == "__main__": + main() diff --git a/news.png b/news.png new file mode 100644 index 0000000..ca91891 Binary files /dev/null and b/news.png differ diff --git a/news.txt b/news.txt new file mode 100644 index 0000000..890596c --- /dev/null +++ b/news.txt @@ -0,0 +1,22 @@ +스페인발 영국행 비행기에서 여객기가 너무 무거워 묵 뜨며 탐승객들에게 약 70만원은 제시 +하며 하차를 요구하는 일이 빌생했다 + +10일(현지시간) 인디펜던트 등에 따르면 이는 지난 5일 스페인 란사로테 공항을 떠나 영국 리버 +풀 존 레넌 공항으로 갈 예정이던 영국 저가 항공사 이지젯의 6273364편(에어버스 4320-200 +기)에서 일어났다. + +이 비행기는 당초 오후 9시 45분에 줄발 예정이었지만 시간이 다 돼도 움직이지 않았다. 얼마 뒤 +기장이 안내방송을 시작하더니 “승객이 너무 많이 탑승해 항공기가 즐발하기에 너무 무겁다"고 +지연 사유를 밝혔다. + +기장은 “이 공항은 활주로가 짧은 데다가 바람 방향도 좋지 않아 여러 불리한 조건이 겹쳤다”며 +논의 끝에 기체를 가변게 만들어야 한다는 결론을 내리게 됐다”고 설명했다. + +그는 “최대 20명의 승객이 내리기를 간곡히 요정드린다 하자를 자원한 분께는 1인당 최대 500 +유로(약71만 원)의 인센티브를 드리겠다"고 제안했다 + +항공사 이지젯에 따르면 이날 비행기에서 내리겠다고 밝 몬 승객은 종 19명이다. 이지젯은 승객 +들에게는 비용이 지불했다고 전했으나, 약속한 500유로인지는 밝히지 않았다. + +이지젯은 “이같은 상황에서 내릴 적절한 운영 결정이다. 모든 항공사가 안전상의 이유로 중량 제 +한을 시행하고 있다"고 전했다. diff --git a/python_formmail_smtp.py b/python_formmail_smtp.py new file mode 100644 index 0000000..7217edd --- /dev/null +++ b/python_formmail_smtp.py @@ -0,0 +1,96 @@ +from flask import Flask, request +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from email.mime.base import MIMEBase +from email import encoders + +app = Flask(__name__) + +@app.route("/", methods=["GET", "POST"]) +def index(): + if request.method == "POST": + name = request.form.get("name") + phone = request.form.get("phone") + email = request.form.get("email") + memo = request.form.get("memo") + file1 = request.files.get("file1") + file2 = request.files.get("file2") + + msg = MIMEMultipart() + msg['From'] = "id@naver.com" + msg['To'] = "id@naver.com" + msg['Subject'] = "Formmail" + + body = f"Name: {name}\nPhone: {phone}\nEmail: {email}\nMemo: {memo}" + msg.attach(MIMEText(body, 'plain')) + + if file1: + filename = file1.filename + attachment = MIMEBase('application', "octet-stream") + attachment.set_payload((file1.read())) + encoders.encode_base64(attachment) + attachment.add_header('Content-Disposition', f'attachment; filename= {filename}') + msg.attach(attachment) + + if file2: + filename = file2.filename + attachment = MIMEBase('application', "octet-stream") + attachment.set_payload((file2.read())) + encoders.encode_base64(attachment) + attachment.add_header('Content-Disposition', f'attachment; filename= {filename}') + msg.attach(attachment) + + server = smtplib.SMTP('smtp.naver.com', 587) + server.ehlo() + server.starttls() + server.ehlo() + server.login("id@naver.com", "password") + text = msg.as_string() + server.sendmail("id@naver.com", "id@naver.com", text) + server.quit() + + return "Form submitted!" + + return """ + + + Formmail + + +

Formmail

+
+

+ + +

+

+ + +

+

+ + +

+

+ + +

+

+ + +

+

+ + +

+

+ +

+
+ + + """ + +if __name__ == "__main__": + app.run() \ No newline at end of file diff --git a/send_fcm_coupang_multicast.py b/send_fcm_coupang_multicast.py new file mode 100644 index 0000000..d790e93 --- /dev/null +++ b/send_fcm_coupang_multicast.py @@ -0,0 +1,27 @@ +import firebase_admin +from firebase_admin import credentials +from firebase_admin import messaging + +cred_path = "coupang-b83fe-firebase-adminsdk-7mcpg-0967b8e8cd.json" +cred = credentials.Certificate(cred_path) +default_app = firebase_admin.initialize_app(cred) + +registration_tokens = ['fMtg9MuSTBi80CWFjH3ShU:APA91bFwQlHt_Ratbt2CwjBi4coEFFj3IoY5xGZbcU_mBANs-cH4001Dg1H_jadQumV3bixqlAClmuTevP6ZvvtpZqXLO79x6Jw4edz7pY9DiK1u9BWenlUz196vTcZsksypJpA-QumC', + 'f1jcyan9RLWLKa77ZFvVaz:APA91bGTmueB6iQFyKkaWJqI9xnIbMZ_qp2S0tR7hkMvERE4VCyag5tZPgybeRTnb3R7ai6pj8zDXLxHyUu9qzrQWSmoQVjEcKunvSvs1CkGXU2dkGm7SEL_PtX2XByJYtlM0k8MyoFW'] + +message = messaging.MulticastMessage( + notification=messaging.Notification( + title='test', + body='python push test', + image='https://icnu.kr/coupang/logo.png' + ), + data = { + 'title':'test', + 'message':'python fcm test', + 'mode':'test', + 'data':'12345' + }, + tokens=registration_tokens, +) +response = messaging.send_multicast(message) +print('Successfully sent message:', response) \ No newline at end of file diff --git a/send_fcm_coupang_topic.py b/send_fcm_coupang_topic.py new file mode 100644 index 0000000..a3ddce6 --- /dev/null +++ b/send_fcm_coupang_topic.py @@ -0,0 +1,28 @@ +# https://github.com/firebase/firebase-admin-python/blob/master/snippets/messaging/cloud_messaging.py + +import firebase_admin +from firebase_admin import credentials +from firebase_admin import messaging + +cred_path = "coupang-b83fe-firebase-adminsdk-7mcpg-0967b8e8cd.json" +cred = credentials.Certificate(cred_path) +default_app = firebase_admin.initialize_app(cred) + +topic = 'testTopic' + +message = messaging.Message( + notification=messaging.Notification( + title='test', + body='python push test', + image='https://icnu.kr/coupang/logo.png' + ), + data = { + 'title':'test', + 'message':'python fcm test', + 'mode':'test', + 'data':'12345' + }, + topic=topic, +) +response = messaging.send(message) +print('Successfully sent message:', response) \ No newline at end of file diff --git a/send_fcm_coupang_unicast.py b/send_fcm_coupang_unicast.py new file mode 100644 index 0000000..a5b3a58 --- /dev/null +++ b/send_fcm_coupang_unicast.py @@ -0,0 +1,29 @@ +# https://github.com/firebase/firebase-admin-python/blob/master/snippets/messaging/cloud_messaging.py + +import firebase_admin +from firebase_admin import credentials +from firebase_admin import messaging + +cred_path = "coupang-b83fe-firebase-adminsdk-7mcpg-0967b8e8cd.json" +cred = credentials.Certificate(cred_path) +default_app = firebase_admin.initialize_app(cred) + +registration_token = 'fMtg9MuSTBi80CWFjH3ShU:APA91bFwQlHt_Ratbt2CwjBi4coEFFj3IoY5xGZbcU_mBANs-cH4001Dg1H_jadQumV3bixqlAClmuTevP6ZvvtpZqXLO79x6Jw4edz7pY9DiK1u9BWenlUz196vTcZsksypJpA-QumC' +# registration_token = 'f1jcyan9RLWLKa77ZFvVaz:APA91bGTmueB6iQFyKkaWJqI9xnIbMZ_qp2S0tR7hkMvERE4VCyag5tZPgybeRTnb3R7ai6pj8zDXLxHyUu9qzrQWSmoQVjEcKunvSvs1CkGXU2dkGm7SEL_PtX2XByJYtlM0k8MyoFW' + +message = messaging.Message( + notification=messaging.Notification( + title='test', + body='python push test', + image='https://icnu.kr/coupang/logo.png' + ), + data = { + 'title':'test', + 'message':'python fcm test', + 'mode':'test', + 'data':'12345' + }, + token=registration_token, +) +response = messaging.send(message) +print('Successfully sent message:', response) \ No newline at end of file diff --git a/smssend.py b/smssend.py new file mode 100644 index 0000000..c9f8945 --- /dev/null +++ b/smssend.py @@ -0,0 +1,51 @@ +import requests + + +class JmunjaPhone: + def __init__(self, uid, upw): + self.uid = uid + self.upw = upw + self.url = "http://jmunja.com/sms/app/api.php" + self.subject = "" + self.content = "" + self.hpno = "" + + def send(self, subject, content, hpno): + self.subject = subject + self.content = content + self.hpno = hpno + + dict_data = {'mode': 'send', 'id': self.uid, 'pw': self.upw, 'title': self.subject, + 'message': self.content, 'reqlist': self.hpno} + response = requests.post(url=self.url, data=dict_data, + headers={'Content-Type': 'application/x-www-form-urlencoded'}) + gubun = ":header_stop:" + result = response.text.replace(gubun, "") + return result + + +class JmunjaWeb: + def __init__(self, uid, upw): + self.uid = uid + self.upw = upw + self.url = "http://jmunja.com/sms/web/api.php" + self.subject = "" + self.content = "" + self.hpno = "" + self.callback = "" + + def send(self, subject, content, hpno, callback): + self.subject = subject + self.content = content + self.hpno = hpno + self.callback = callback + + dict_data = {'mode': 'send', 'id': self.uid, 'pw': self.upw, 'title': self.subject, + 'message': self.content, 'reqlist': self.hpno, 'callback': self.callback} + response = requests.post(url=self.url, data=dict_data, + headers={'Content-Type': 'application/x-www-form-urlencoded'}) + gubun = ":header_stop:" + result = response.text.replace(gubun, "") + return result + + diff --git a/tesseract_ocr.py b/tesseract_ocr.py new file mode 100644 index 0000000..02e55a7 --- /dev/null +++ b/tesseract_ocr.py @@ -0,0 +1,54 @@ +""" +Tesseract 다운로드 +https://tesseract-ocr.github.io/tessdoc/Installation.html + +윈도우 OS 사용자의 경우 아래 링크에서 다운받으세요. +https://github.com/UB-Mannheim/tesseract/wiki +https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-5.3.0.20221222.exe + +OS에 맞는 설치 파일을 다운로드 후 설치하세요. + +설치 후 Tesseract 설치 경로를 Path에 추가합니다. +Tesseract 설치 경로 기본값: C:\Program Files\Tesseract-OCR +Path 설치 방법: https://blog.naver.com/oralol/222472012941 + +[파이썬] +* opencv 설치: pip install opencv-python +* pytesseract 설치: pip install pytesseract +pip 실행이 안될 경우 python -m pip 으로 해보시기 바랍니다. + +* OEM(OCR Engine Mode) +0 레거시 엔진 +1 신경망 LSTM 엔진 +2 레거시+LSTM +3 기본값 + +* PSM(Page Segmentation Mode) +0 방향 및 스크립트 감지(OSD) 전용. +1 OSD를 통한 자동 페이지 분할. +2 자동 페이지 분할, OSD 또는 OCR 없음. +3 완전 자동 페이지 분할이지만 OSD는 없습니다. (기본값) +4 다양한 크기의 단일 텍스트 열을 가정합니다. +5 세로로 정렬된 텍스트의 단일 균일 블록을 가정합니다. +6 하나의 균일한 텍스트 블록을 가정합니다. +7 이미지를 단일 텍스트 줄로 처리합니다. +8 이미지를 한 단어로 취급합니다. +9 이미지를 원 안의 한 단어로 취급합니다. +10 이미지를 단일 문자로 처리합니다. +11 희소 텍스트. 특정 순서 없이 가능한 한 많은 텍스트를 찾습니다. +12 OSD가 포함된 희소 텍스트. +13 원시 라인. 이미지를 단일 텍스트 줄로 취급하여 Tesseract에 특정한 핵을 우회합니다. +""" + +import cv2 +import pytesseract + +pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe' +img = cv2.imread('test.png') +my_config = "-l eng+kor --oem 3 --psm 6" +# my_config = "--oem 3 --psm 6 outputbase digits" +# my_config = "-c tessedit_char_whitelist=0123456789 --oem 3 --psm 6" +# my_config = "-c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyz --oem 3 --psm 6" +# my_config = "-c tessedit_char_blacklist=0123456789 --oem 3 --psm 6" +result = pytesseract.image_to_string(img, config=my_config) +print(result) diff --git a/tesseract_ocr_sample.py b/tesseract_ocr_sample.py new file mode 100644 index 0000000..45bdc0a --- /dev/null +++ b/tesseract_ocr_sample.py @@ -0,0 +1,12 @@ +# pip install pytesseract + +from PIL import Image +import pytesseract + +pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' +text = pytesseract.image_to_string(Image.open("news.png"), lang="kor") +print(text) + +with open("news.txt", "w", encoding="utf8") as f: + f.write(text) + diff --git a/tesseract_oct.py b/tesseract_oct.py new file mode 100644 index 0000000..45bdc0a --- /dev/null +++ b/tesseract_oct.py @@ -0,0 +1,12 @@ +# pip install pytesseract + +from PIL import Image +import pytesseract + +pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' +text = pytesseract.image_to_string(Image.open("news.png"), lang="kor") +print(text) + +with open("news.txt", "w", encoding="utf8") as f: + f.write(text) + diff --git a/threading_ex1.py b/threading_ex1.py new file mode 100644 index 0000000..7880f5a --- /dev/null +++ b/threading_ex1.py @@ -0,0 +1,14 @@ +import threading +import requests +import time + +def getHtml(url): + resp = requests.get(url) + time.sleep(3) + print("Sub Thread", url, len(resp.text), 'chars') + +t = threading.Thread(target=getHtml, args=('https://www.naver.com',)) +t.daemon = False +t.start() + +print("Main Thread") \ No newline at end of file diff --git a/threading_ex2.py b/threading_ex2.py new file mode 100644 index 0000000..5d6bb72 --- /dev/null +++ b/threading_ex2.py @@ -0,0 +1,16 @@ +import threading, requests, time + +class HtmlGetter (threading.Thread): + def __init__(self, url): + threading.Thread.__init__(self) + self.url = url + + def run(self): + resp = requests.get(self.url) + time.sleep(3) + print("Sub Thread", self.url, len(resp.text), 'chars') + +t = HtmlGetter('https://www.naver.com') +t.start() + +print("Main Thread") \ No newline at end of file