오늘 내가 배운 것을 정리하자
190527 - walkWithPython
Pycharm, Python, Git Bash 설치
Pycharm에 Git bash 연동
.gitignore
프로젝트 업로드
마크다운 작성
Typora
끝말잇기
점심시간
stirng_interpolation.py : 문자열
- 옛날 방식
pyformatf-string
lotto.py : random 이용한 로또뽑기
write_txt.py : 파일 쓰기
open()with open()
2-1.writelines
Escape Sequence
read_txt.py : 파일 읽기
open files()with open()
reverse_content.py : 파일 수정
read filereversewrite files
for : range 종료시 매개변수 값
naver_rank.py : bs4 사용한 크롤링 활용
requests,bs4,datetime,encoding,enumerate
write_csv.py : csv 파일 쓰기
f-stringjoin()csv
read_csv.py : csv 파일 읽기
stringsplitcsv
melon_rank.py : melon에서 실시간 차트 가져오자
190528 - Web
Static Web
Dynamic Web
URL 구조
URL과 URI 차이
HTML -> HTTP
HTML Tag
headernavasidesectionarticlefooter
non-Semantic Tag
div
heading
paragraph
brhr
font-style
b,strongi,emdel
list
ol+liul+li
a: 상대경로, 절대경로, id, mailto, _blank
media
imgiframe
form
input: text, password, submit
추가적인 학습 : MDN HTML Tag, poiemaweb, velopert
fake_naver.html : form태그와 query를 활용해 fake 네이버 검색창 만들기
css 도입
css 선언
- external
- internal
- inline
css 선택자
tag*idclassparent > child
css 우선순위
!importantcss inline선언idclasstagparent에 의해 상속
font
font-sizefont-stylefont-weightfont-family
google font
Bootstrap
CDN
실제로 써보자
m-3,p-4,mx-3,py-4text-center,text-primarycontainergrid=row,column+emmetborderbtn,btn-primaryform
수강자가 만드는 Github Pages
Github Pages 실습
190529 - WebService
Web Service 도입
WWW : World Wide Web
현실세계의 Service -> Web Service
Client, Server
Get, Post
Python + Flask
$ pip install Flask
$ FLASK_APP=hello.py flask run$ FLASK_DEBUG=1 FLASK_APP=hello.py flask runhello.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/mulcam")
def mulcam():
return "This is Multicampus"
# Flask를 쉽게 켜자
if __name__ == '__main__':
app.run(debug=True)명령어가 많이 줄어듬
$ python hello.py__name__
import, def
decorator: bye.py
variable routing, path variable
stringint
사람 수 만큼 점심메뉴 뽑기
- 메뉴 수 보다 많은 사람 수?
- 중복 가능하도록?
hello.py
from flask import Flask
from random import sample
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/mulcam")
def mulcam():
return "This is Multicampus"
@app.route("/greeting/<string:name>")
def greeting(name):
return f'반갑습니다. {name}!'
@app.route("/cube/<int:num>")
def cube(num):
result = num ** 3
return f'{num}의 세제곱은 {result}'
# 사람 수 만큼 점심 메뉴 추천
@app.route("/lunch/<int:people>")
def lunch(people):
menu = ["짜장면", "짬뽕", "라면", "브리또", "사과", "찜닭"]
return f'{sample(menu, people)}'
# Flask를 쉽게 켜자
if __name__ == '__main__':
app.run(debug=True)랜더링
html tag@app.route("/html") def html(): multiple_string = """ <h1>This is HTML</h1> <p>This is p tag</p> """ return multiple_string
.html+/templates+render_template@app.route("/html_file") def html_file(): return render_template('html_file.html')
Template Variable-jinja@app.route("/hi/<string:name>") def hi(name): # Template Variable return render_template('hi.html', your_name=name)
html파일에서 파이썬 문법 사용하기
{% for menu in menu_list %}
<li>{{ menu }}</li>
{% endfor %}send # form => receive
request.arg.get
신이 나를 만들 때 같이
URL로 정보 넘기기 실습
JSON
dict
- dict 생성
- dict item 추가
- dict value 가져오기
- dict 반복문 활용 4-1. 기본 4-2. key 반복 4-3. value 반복 4-4. key, value 반복
lotto
lotto API, requests, JSON, append
list comprehension
회차 입력
@app.route('/lotto_check')
def lotto_check():
return render_template('lotto_check.html')
@app.route('/lotto_result')
def lotto_result():
lotto_round = request.args.get('lotto_round')
url = f"https://dhlottery.co.kr/common.do?method=getLottoNumber&drwNo={lotto_round}"
response = requests.get(url)
# response.text # => string
lotto = response.json() # => dict
winner = []
# list comprehension
# a = [n*2 for n in range(1, 7)] # => [2, 4, 6, 8, 10, 12]
a = [lotto[f'drwtNo{n}'] for n in range(1, 7)]
bonus = lotto['bnusNo']
winner = f'{a} + {bonus}'
return render_template('lotto_result.html', lotto=winner, bonus=bonus)등수 확인
Set = {요소1, 요소2, ...} : 집합
&(합집합),|(교집합)
in, len
190530 - TelegramBot
Telegram
@botfather: /newbot, token
available methods
getMesendMessagegetUpdatesid
API를 활용해 봇에 메시지 날리기
pythonrequests,inputflask
챗봇 만들자
return body, status_code, POST
ngrok : 인터넷과 내 로걸 서버를 연결
ngrok.exe 파일은 사용자 폴더로 옮겨 실행한다
win 10에서 ngrok이 잘 안되는 경우
equinox에서 2.2.8 버전으로 진행해보자
available methods
setWebhook
메아리치는 봇
request.args# GETrequest.forms# POSTrequest.get_json()
로또 외치면 로또 번호
is vs ==
1000 is 10**3 # FALSE
# 띄어쓰기 없는 짧은 문자의 경우는 다를 수 있다
a = 'lotto lotto'
b = 'lotto lotto'
id(a) # 4437766384
id(b) # 4437766448
a is b # FALSE
-5 ~ 255 # 자주 쓰는 숫자는 메모리에 이미 넣어둠JSON에서 번역할 문자열 찾기
get('message').get('result').get('translatedText')
명령어 추가
text[0:4] == '/번역 '
python-decouple
Key 관리합니다
pip install python-decouplepythonanywhere 통해 배포