├── .gitattributes ├── .gitignore ├── 예제 소스 코드 ├── 02교시 │ ├── breadcount.py │ ├── function_sample.py │ ├── library_sample.py │ ├── upper_method.py │ ├── writefile.py │ └── wx_sample.py ├── 04교시 │ ├── cxoracle_sample.py │ ├── pymongo_sample.py │ ├── pymssql_sample.py │ ├── pymysql_sample.py │ ├── pyodbc_sample.py │ ├── sqlite3_sample.py │ └── 미니문법 │ │ ├── for_enumerate.py │ │ ├── for_list.py │ │ ├── for_range1.py │ │ ├── for_range2.py │ │ ├── if_sample.py │ │ ├── string_sample.py │ │ └── while_sample.py ├── 05교시 │ ├── pycrypto_aes256_sample.py │ └── 미니문법 │ │ ├── function_basic.py │ │ ├── function_multiple_return.py │ │ ├── lambda_function_basic.py │ │ └── lambda_function_filter.py ├── 06교시 │ └── mix_version.py ├── 07교시 부록 │ ├── excel_from_database_function.py │ └── 미니문법 │ │ ├── escape_nouse.py │ │ └── escape_use.py ├── 07교시 │ ├── excel_from_database.py │ ├── excel_from_database_by_number.py │ ├── excel_read.py │ └── excel_sample.py ├── 08교시 │ ├── reg.txt │ ├── reg2.txt │ ├── reg_sample1.py │ ├── reg_sample2.py │ ├── reg_sample3.py │ ├── reg_sample4.py │ ├── reg_sample5.py │ └── 미니문법 │ │ ├── dictionary_sample.py │ │ ├── list_sample.py │ │ └── tuple_sample.py ├── 09교시 │ ├── wx_encryption.py │ └── 미니문법 │ │ └── class_sample.py ├── 10교시 │ ├── ip.txt │ ├── whois_iptest.py │ ├── whoisapi_1st.py │ ├── whoisapi_2nd.py │ ├── whoisapi_3rd.py │ └── 미니문법 │ │ ├── except_sample.py │ │ ├── file_readlines.py │ │ ├── file_write.py │ │ ├── global_variable.py │ │ ├── ip.txt │ │ ├── json_dumps.py │ │ ├── json_loads.py │ │ └── with_sample.py ├── 11교시 │ ├── beautiful.py │ └── whois_call_jscfile.py ├── 12교시 │ ├── selenium_1st.py │ ├── selenium_2nd.py │ ├── selenium_3rd.py │ ├── selenium_4th.py │ ├── selenium_firefox.py │ ├── selenium_ie.py │ ├── selenium_phantom_1st.py │ ├── selenium_phantom_2nd.py │ ├── selenium_phantom_3rd.py │ ├── selenium_phantom_4th.py │ └── selenium_phantom_final.py ├── 13교시 │ ├── naver_upload.py │ ├── notepad1.py │ ├── notepad2.py │ ├── notepad3.py │ ├── notepad4.py │ ├── notepad5.py │ └── notepad_final.py ├── 14교시 │ ├── 14교시 샘플.zip │ ├── ftpupload_final.py │ ├── ftpuploadtest.py │ ├── ziptest.py │ ├── ziptest2.py │ └── 미니문법 │ │ ├── datetime_sample.py │ │ ├── ftpupload_final_use_run.py │ │ └── os_sample.py ├── 15교시 │ ├── numpy_test.py │ ├── pandas_test.py │ ├── scipy_test.py │ └── sympy_test.py ├── 16교시 │ ├── matplotlib_test.py │ ├── plotly_offline.py │ └── plotly_online.py ├── 17교시 │ ├── least_numpy_sample.py │ ├── least_scipy_sample.py │ ├── least_tensorflow_sample.py │ └── opencv_fft_sample.py ├── 18교시 │ ├── ASP │ │ ├── ajax_sample.asp │ │ ├── ajax_sub.asp │ │ ├── supermarket_sample.asp │ │ └── test.asp │ ├── HTML │ │ ├── css_sample.html │ │ ├── font_sample.html │ │ ├── form_sample.html │ │ ├── table_sample1.html │ │ ├── table_sample2.html │ │ └── table_sample3.html │ └── JavaScript │ │ ├── colorchange_sample.html │ │ └── menu_sample.html ├── 19교시 │ └── flaskweb │ │ ├── myweb.py │ │ ├── myweb_d3.py │ │ ├── myweb_mat.py │ │ └── templates │ │ ├── d3sample.html │ │ ├── mypic.html │ │ └── myweb.html ├── 20교시 │ ├── djangoweb │ │ ├── db.sqlite3 │ │ ├── djangoweb │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── settings.cpython-36.pyc │ │ │ │ ├── urls.cpython-36.pyc │ │ │ │ └── wsgi.cpython-36.pyc │ │ │ ├── settings.py │ │ │ ├── urls.py │ │ │ └── wsgi.py │ │ ├── manage.py │ │ └── supermarket │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ │ ├── admin.py │ │ │ ├── apps.py │ │ │ ├── migrations │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ │ └── __init__.cpython-36.pyc │ │ │ ├── models.py │ │ │ ├── templates │ │ │ ├── d3sample.html │ │ │ ├── index.html │ │ │ └── super.html │ │ │ ├── tests.py │ │ │ ├── urls.py │ │ │ └── views.py │ └── djangoweb_json_modify │ │ ├── db.sqlite3 │ │ ├── djangoweb │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ │ ├── manage.py │ │ └── supermarket │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── admin.cpython-36.pyc │ │ ├── models.cpython-36.pyc │ │ ├── urls.cpython-36.pyc │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ └── __init__.cpython-36.pyc │ │ ├── models.py │ │ ├── templates │ │ ├── d3sample.html │ │ ├── index.html │ │ └── super.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py └── query 모음 │ ├── query_01.txt │ ├── query_02.txt │ ├── query_03.txt │ ├── query_04.txt │ ├── query_05.txt │ ├── query_06.txt │ ├── query_07.txt │ ├── query_08.txt │ ├── query_09.txt │ ├── query_10.txt │ ├── query_11.txt │ ├── query_12.txt │ ├── query_13.txt │ ├── query_14.txt │ ├── query_15.txt │ ├── query_16.txt │ └── query_17.txt └── 책속 링크 모음.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /예제 소스 코드/02교시/breadcount.py: -------------------------------------------------------------------------------- 1 | bread_friend = [2, 3, 4, 5, 6] 2 | bread_friend_sum = sum(bread_friend, 0.0) 3 | print(bread_friend_sum) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/02교시/function_sample.py: -------------------------------------------------------------------------------- 1 | def myfn(x): 2 | if x > 100: 3 | print("over 100") 4 | else: 5 | print("under 100") 6 | 7 | 8 | myfn(120) 9 | myfn(90) 10 | -------------------------------------------------------------------------------- /예제 소스 코드/02교시/library_sample.py: -------------------------------------------------------------------------------- 1 | import statistics 2 | 3 | data = [3, 7, 4, 6] 4 | print (statistics.mean(data)) 5 | -------------------------------------------------------------------------------- /예제 소스 코드/02교시/upper_method.py: -------------------------------------------------------------------------------- 1 | input = "This is a sample" 2 | result = input.upper() 3 | print(result) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/02교시/writefile.py: -------------------------------------------------------------------------------- 1 | f = open('test.txt', 'w') 2 | f.write("This is a test") 3 | print("file is created") -------------------------------------------------------------------------------- /예제 소스 코드/02교시/wx_sample.py: -------------------------------------------------------------------------------- 1 | import wx 2 | 3 | app = wx.App() 4 | 5 | window = wx.Frame(None, title = "wxPython Frame", size = (300,200)) 6 | panel = wx.Panel(window) 7 | label = wx.StaticText(panel, label = "Hello World", pos = (100,50)) 8 | window.Show(True) 9 | app.MainLoop() 10 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/cxoracle_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import cx_Oracle 3 | 4 | # 데이터베이스에 연결합니다. 5 | dsnStr = cx_Oracle.makedsn("127.0.0.1", "1521", "xe") 6 | con = cx_Oracle.connect(user="pyuser", password="test1234", dsn=dsnStr) 7 | 8 | # 커서를 만듭니다. 9 | cur = con.cursor() 10 | 11 | # 커서에 쿼리를 입력해 실행 시킵니다 12 | cur.execute('select * from supermarket') 13 | 14 | # 데이타를 모두 가져옵니다. 15 | res = cur.fetchall() 16 | 17 | # 가져온 내용을 한 줄씩 가져와서, 각 컬럼의 내용을 공백으로 구분해 출력합니다. 18 | for row in res: 19 | print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4])) 20 | 21 | # 연결을 닫습니다. 22 | cur.close() 23 | con.close() -------------------------------------------------------------------------------- /예제 소스 코드/04교시/pymongo_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import json 3 | import pymongo 4 | from pymongo import MongoClient 5 | 6 | # 데이터베이스에 연결합니다. 7 | client = MongoClient("localhost", 27017, maxPoolSize=50) 8 | 9 | # supermarket 컬렉션을 찾습니다. 10 | db=client.admin 11 | collection=db['supermarket'] 12 | cursor = collection.find({},{'_id': False}) 13 | 14 | # 커서를 루프로 돌립니다(i 에는 0 부터 루프의 숫자가 들어갑니다). 15 | for i, document in enumerate(cursor): 16 | rowcontent = "" 17 | keycontent = "" 18 | 19 | # 다큐먼트에서 키와 값을 가져와서 공백으로 구분해 문자열로 만듭니다. 20 | for key, val in document.items(): 21 | keycontent = keycontent + " " + str(key) 22 | rowcontent = rowcontent + " " + str(val) 23 | 24 | # 만약 첫 번째 루프라면 키 이름도 출력해 칼럼 이름 출력하는 것을 흉내냅니다. 25 | if i == 0: 26 | print(keycontent) 27 | print (rowcontent) 28 | else: 29 | print (rowcontent) 30 | i += 1 -------------------------------------------------------------------------------- /예제 소스 코드/04교시/pymssql_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import pymssql 3 | 4 | # 데이터베이스에 연결합니다. 5 | conn = pymssql.connect(server='localhost', user='pyuser', password='test1234', database='mytest') 6 | 7 | # 커서를 만듭니다. 8 | cursor = conn.cursor() 9 | 10 | # 커서에 쿼리를 입력해 실행 시킵니다. 11 | cursor.execute('SELECT Itemno, Category, FoodName, Company, Price FROM supermarket(nolock);') 12 | 13 | # 한 행을 가져옵니다. 14 | row = cursor.fetchone() 15 | 16 | # 행이 존재할 때까지, 하나씩 행을 증가시키면서 1번째 컬럼을 숫자 2째번 컬럼을 문자로 출력합니다. 17 | while row: 18 | print("ID=%d, Category=%s" % (row[0], row[1])) 19 | row = cursor.fetchone() 20 | 21 | #연결을 닫습니다. 22 | conn.close() -------------------------------------------------------------------------------- /예제 소스 코드/04교시/pymysql_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import pymysql 3 | 4 | # 연결 문자열을 세팅합니다. 5 | server = 'localhost' 6 | user = 'pyuser' 7 | password = 'test1234' 8 | dbname = 'mytest' 9 | 10 | # 데이터베이스에 연결합니다. 11 | conn = pymysql.connect(server, user, password, dbname, charset='utf8') 12 | 13 | # 커서를 만듭니다. 14 | cursor = conn.cursor() 15 | 16 | # 커서에 쿼리를 입력해 실행 시킵니다. 17 | cursor.execute('SELECT * FROM supermarket;') 18 | 19 | # 한 행을 가져옵니다. 20 | row = cursor.fetchone() 21 | 22 | # 행이 존재할 때까지, 하나씩 행을 증가시키면서 모든 컬럼을 공백으로 구분해 출력합니다. 23 | while row: 24 | print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4])) 25 | row = cursor.fetchone() 26 | 27 | # 연결을 닫습니다. 28 | conn.close() 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/pyodbc_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import pyodbc 3 | 4 | # 연결 문자열을 세팅합니다. 5 | server = 'localhost' 6 | database = 'mytest' 7 | username = 'pyuser' 8 | password = 'test1234' 9 | 10 | # 데이터베이스에 연결합니다. 11 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 12 | 13 | # 커서를 만든다. 14 | cursor = cnxn.cursor() 15 | 16 | # 커서에 쿼리를 입력해 실행 시킵니다. 17 | tsql = "SELECT * FROM supermarket" 18 | with cursor.execute(tsql): 19 | # 한 행을 가져옵니다, 20 | row = cursor.fetchone() 21 | 22 | # 행이 존재할 때까지, 하나씩 행을 증가시키면서 모든 컬럼을 공백으로 구분해 출력합니다. 23 | while row: 24 | print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4])) 25 | row = cursor.fetchone() 26 | 27 | # 연결을 닫습니다. 28 | cnxn.close() -------------------------------------------------------------------------------- /예제 소스 코드/04교시/sqlite3_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import sqlite3 3 | 4 | # test.db 연결합니다(SQLite 는 없으면 자동으로 생성합니다). 5 | conn = sqlite3.connect("test.db", isolation_level=None) 6 | cursor = conn.cursor() 7 | 8 | 9 | # 테이블이 없다면 해당 테이블을 생성합니다. 10 | cursor.execute("""CREATE TABLE IF NOT EXISTS supermarket(Itemno INTEGER, Category TEXT, 11 | FoodName TEXT, Company TEXT, Price INTEGER)""") 12 | 13 | # 테이블의 내용을 모두 지웁니다. 14 | sql = "DELETE FROM supermarket" 15 | cursor.execute(sql) 16 | 17 | # 테이터를 2건 입력 합니다. 18 | sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)" 19 | cursor.execute(sql, (1, '과일', '자몽', '마트', 1500)) 20 | 21 | sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)" 22 | cursor.execute(sql, (2, '음료수', '망고주스', '편의점', 1000)) 23 | 24 | # 입력된 데이터를 조회합니다. 25 | sql = "select Itemno, Category, FoodName, Company, Price from supermarket" 26 | cursor.execute(sql) 27 | 28 | 29 | # 데이타를 모두 가져옵니다. 30 | rows = cursor.fetchall() 31 | 32 | # 가져온 내용을 한 줄씩 가져와서, 각 컬럼의 내용을 공백으로 구분해 출력합니다. 33 | for row in rows: 34 | print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4])) 35 | 36 | # 연결을 닫습니다. 37 | conn.close() -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/for_enumerate.py: -------------------------------------------------------------------------------- 1 | my_list = ["a", "b", "c"] 2 | 3 | for i, item in enumerate(my_list): 4 | print(i) 5 | print(item) 6 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/for_list.py: -------------------------------------------------------------------------------- 1 | my_list = [1, 2, 3] 2 | for i in my_list: 3 | print(i) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/for_range1.py: -------------------------------------------------------------------------------- 1 | for i in range(3): 2 | print(i) 3 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/for_range2.py: -------------------------------------------------------------------------------- 1 | mylist = [1, 2, 3] 2 | for i in mylist: 3 | print(i) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/if_sample.py: -------------------------------------------------------------------------------- 1 | for i in range(1, 4): 2 | if i == 3: 3 | print(i) 4 | 5 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/string_sample.py: -------------------------------------------------------------------------------- 1 | my_string = " the dog " 2 | print(my_string) 3 | print(my_string.strip().upper()) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/04교시/미니문법/while_sample.py: -------------------------------------------------------------------------------- 1 | i = 1 2 | while (i <= 3): 3 | print (i) 4 | i = i + 1 -------------------------------------------------------------------------------- /예제 소스 코드/05교시/pycrypto_aes256_sample.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import base64 3 | import hashlib 4 | from Crypto import Random 5 | from Crypto.Cipher import AES 6 | 7 | # 암호화할 문자열을 일정 크기로 나누기 위해서, 모자란 경우 크기를 채워줍니다. 8 | BS = 16 9 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode() 10 | unpad = lambda s : s[0:-s[-1]] 11 | 12 | 13 | # 암호화를 담당할 클래스 입니다. 14 | class AESCipher: 15 | 16 | # 클래스 초기화 - 전달 받은 키를 해시 값으로 변환해 키로 사용합니다. 17 | def __init__( self, key ): 18 | self.key = key 19 | self.key = hashlib.sha256(key.encode()).digest() 20 | 21 | # 암호화 - 전달받은 평문을 패딩 후, AES 256 으로 암호화 합니다. 22 | def encrypt( self, raw ): 23 | raw = raw.encode() 24 | raw = pad(raw) 25 | iv = Random.new().read( AES.block_size ) 26 | cipher = AES.new( self.key, AES.MODE_CBC, iv ) 27 | return base64.b64encode( iv + cipher.encrypt( raw ) ).decode() 28 | 29 | # 복호화 - 전달 받은 값을 복호화 한후, 언패딩해 원문을 전달합니다. 30 | def decrypt( self, enc ): 31 | enc = base64.b64decode(enc) 32 | iv = enc[:16] 33 | cipher = AES.new(self.key, AES.MODE_CBC, iv ) 34 | return unpad(cipher.decrypt( enc[16:] )).decode() 35 | 36 | 37 | # 암호화 클래스를 이용해 cipherinstance 객체를 만들면서, 암호화키를 넣습니다. 38 | cipherinstance = AESCipher('mysecretpassword') 39 | 40 | # 암호화를 합니다. 41 | encrypted = cipherinstance.encrypt('감추고 싶은 말') 42 | 43 | # 암호화 한 값을 다시 복호화 합니다. 44 | decrypted = cipherinstance.decrypt(encrypted) 45 | 46 | # 암호화 한 값과 복호화 한 값을 출력 합니다. 47 | print('암호화된 값 : ' + encrypted) 48 | print('복호화된 값 : ' + decrypted) -------------------------------------------------------------------------------- /예제 소스 코드/05교시/미니문법/function_basic.py: -------------------------------------------------------------------------------- 1 | def muliply_by_two(loopnum): 2 | return loopnum*2 3 | 4 | 5 | my_list = [1, 2, 3] 6 | for i in my_list: 7 | print(muliply_by_two(i)) 8 | -------------------------------------------------------------------------------- /예제 소스 코드/05교시/미니문법/function_multiple_return.py: -------------------------------------------------------------------------------- 1 | def muliply_by_two(loopnum): 2 | return loopnum, loopnum*2 3 | 4 | 5 | my_list = [1, 2, 3] 6 | for i in my_list: 7 | original, changed = muliply_by_two(i) 8 | print(original) 9 | print(changed) 10 | -------------------------------------------------------------------------------- /예제 소스 코드/05교시/미니문법/lambda_function_basic.py: -------------------------------------------------------------------------------- 1 | multiply_by_two = lambda loopnum:loopnum*2 2 | 3 | my_list = [1, 2, 3] 4 | for i in my_list: 5 | print(multiply_by_two(i)) 6 | -------------------------------------------------------------------------------- /예제 소스 코드/05교시/미니문법/lambda_function_filter.py: -------------------------------------------------------------------------------- 1 | my_list = [1, 2, 3] 2 | results = filter(lambda x: x < 3, my_list) 3 | 4 | for result in results: 5 | print(result) 6 | -------------------------------------------------------------------------------- /예제 소스 코드/06교시/mix_version.py: -------------------------------------------------------------------------------- 1 | # 모듈을 불러옵니다. 2 | import base64 3 | import pyodbc 4 | import hashlib 5 | from Crypto import Random 6 | from Crypto.Cipher import AES 7 | 8 | # 암호화된 문자열을 특정한 블록으로 잘라 연산하기 위해서 블록의 길이를 맞춰주는 코드입니다. 9 | BS = 16 10 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode() 11 | unpad = lambda s : s[0:-s[-1]] 12 | 13 | 14 | # 암호화를 담당할 클래스 입니다. 15 | class AESCipher: 16 | 17 | # 클래스 초기화 - 전달 받은 키를 해시 값으로 변환해 키로 사용합니다. 18 | def __init__( self, key ): 19 | self.key = hashlib.sha256(key.encode()).digest() 20 | 21 | # 암호화 - 전달받은 평문을 패딩 후, AES 256 으로 암호화 합니다. 22 | def encrypt( self, raw ): 23 | raw = raw.encode() 24 | raw = pad(raw) 25 | iv = Random.new().read( AES.block_size ) 26 | cipher = AES.new( self.key, AES.MODE_CBC, iv ) 27 | return base64.b64encode( iv + cipher.encrypt( raw ) ).decode() 28 | 29 | # 복호화 - 전달 받은 값을 복호화 한후, 언패딩해 원문을 전달합니다. 30 | def decrypt( self, enc ): 31 | enc = base64.b64decode(enc) 32 | iv = enc[:16] 33 | cipher = AES.new(self.key, AES.MODE_CBC, iv ) 34 | return unpad(cipher.decrypt( enc[16:] )).decode() 35 | 36 | # 암호화 클래스를 이용해 cipherinstance 인스턴트를 만들면서, 암호화키를 넣습니다. 37 | cipherinstance = AESCipher('mysecretpassword') 38 | 39 | 40 | # 데이터베이스 연결 커넥션을 만듭니다. 41 | server = 'localhost' 42 | database = 'mytest' 43 | username = 'pyuser' 44 | password = 'test1234' 45 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 46 | 47 | # 커서를 생성 합니다. 48 | cursor = cnxn.cursor() 49 | 50 | #### 1 51 | # play 테이블에서 original 컬럼을 조회합니다. 52 | cursor.execute('SELECT original FROM play(nolock);') 53 | row = cursor.fetchone() 54 | original = str(row[0]) 55 | 56 | # original 컬럼 값을 암호화 합니다. 57 | encrypted = cipherinstance.encrypt(original) 58 | 59 | # 암호화한 값을 encrypted 컬럼에 업데이트를 합니다. 60 | cursor.execute("update play set encrypted = ? where original='비밀 문구'", encrypted) 61 | cnxn.commit() 62 | 63 | #### 2 64 | # encrypted 컬럼을 조회합니다. 65 | cursor.execute('SELECT encrypted FROM play(nolock);') 66 | row = cursor.fetchone() 67 | encrypted_select = str(row[0]) 68 | 69 | # encrypted 컬럼 값을 복호화 합니다. 70 | decrypted_insert = cipherinstance.decrypt(encrypted_select) 71 | 72 | # 복호화 한 값을 decrypted 필드에 업데이트 합니다. 73 | cursor.execute("update play set decrypted = ? where original='비밀 문구'", decrypted_insert) 74 | cnxn.commit() 75 | 76 | #### 3 77 | # 모든 컬럼을 조회해서 줄로 나누어('\n') 출력합니다. strip() 함수는 문자열 양쪽의 공백을 없애줍니다. 78 | cursor.execute('SELECT * FROM play(nolock);') 79 | row = cursor.fetchone() 80 | while row: 81 | print ('original : ' + str(row[0]) + "\n" + 'encrypted : ' 82 | + str(row[1]).strip() + "\n" + 'decrypted : ' + str(row[2])) 83 | row = cursor.fetchone() 84 | -------------------------------------------------------------------------------- /예제 소스 코드/07교시 부록/excel_from_database_function.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | from openpyxl import load_workbook 3 | # 모듈 호환 에러가 나서 주석 처리 합니다. 4 | #from openpyxl.compat import range 5 | import pyodbc 6 | 7 | # 워크북을 하나 만듭니다. 8 | wb = Workbook() 9 | 10 | # 활성화된 엑셀 시트를 선택합니다. 11 | ws = wb.active 12 | 13 | # 엑셀 제목을 지정합니다. 14 | ws.title = "output" 15 | 16 | # 데이터베이스 연결 문자열을 세팅 합니다. 17 | server = 'localhost' 18 | database = 'mytest' 19 | username = 'pyuser' 20 | password = 'test1234' 21 | 22 | # 데이터 베이스에 연결 합니다. 23 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 24 | 25 | # 커서를 만듭니다. 26 | cursor = cnxn.cursor() 27 | 28 | # 가져올 테이블 이름 변수 입니다. 29 | my_table_name = 'supermarket' 30 | 31 | 32 | # A) 칼럼이름 얻어오기 함수 입니다. 33 | def get_column_name(table_name): 34 | column_name = [] 35 | 36 | cursor.execute('SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = \'' + table_name + '\';') 37 | 38 | row = cursor.fetchone() 39 | while row: 40 | column_name.append(row[0]) 41 | row = cursor.fetchone() 42 | return column_name 43 | 44 | 45 | # B) 칼럼 이름을 엑셀에 저장하는 함수 입니다. 46 | def save_column_name(column_name): 47 | column_char = 'a' 48 | 49 | for name in column_name: 50 | ws[column_char + '1'] = name 51 | column_char = chr(ord(column_char) + 1) 52 | 53 | 54 | # C) select 칼럼 쿼리 제작하는 함수 입니다(Item, Category, ..., Price) 55 | def make_column_query(column_name): 56 | column_query = '' 57 | 58 | for name in column_name: 59 | column_query = column_query + name + ',' 60 | column_query = column_query[:-1] 61 | return column_query 62 | 63 | 64 | # D) 테이블 내용을 엑셀에 저장하는 함수 입니다. 65 | def save_table_content(table_name, column_name): 66 | column_query = make_column_query(column_name) 67 | 68 | cursor.execute('SELECT ' + column_query + ' FROM ' + table_name + '(nolock);') 69 | row = cursor.fetchone() 70 | 71 | row_num = 2 72 | while row: 73 | column_char = 'a' 74 | for x in range(1, len(column_name)+1): #칼럼수 참조하게 변경 75 | ws[column_char + str(row_num)] = row[x-1] 76 | column_char = chr(ord(column_char) + 1) 77 | 78 | row_num = row_num + 1 79 | row = cursor.fetchone() 80 | 81 | ### 만든 함수들 실행 82 | # 칼럼 이름을 얻어옵니다. 83 | my_column_name = get_column_name(my_table_name) 84 | # 칼럼 이름을 저장합니다. 85 | save_column_name(my_column_name) 86 | # 테이블 내용을 저장합니다. 87 | save_table_content(my_table_name, my_column_name) 88 | 89 | # 파일을 실제 저장 합니다. 90 | wb.save("result2.xlsx") 91 | 92 | print("엑셀저장 완료") -------------------------------------------------------------------------------- /예제 소스 코드/07교시 부록/미니문법/escape_nouse.py: -------------------------------------------------------------------------------- 1 | # escape 문자를 사용하지 않습니다. 2 | mystring = "I'm a student" 3 | print(mystring) -------------------------------------------------------------------------------- /예제 소스 코드/07교시 부록/미니문법/escape_use.py: -------------------------------------------------------------------------------- 1 | # escape 문자를 사용 합니다. 2 | mystring = 'I\'m a student' 3 | print(mystring) -------------------------------------------------------------------------------- /예제 소스 코드/07교시/excel_from_database.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | from openpyxl import load_workbook 3 | # 모듈 호환 에러가 나서 주석 처리 합니다. 4 | #from openpyxl.compat import range 5 | import pyodbc 6 | 7 | # 워크북을 하나 만듭니다. 8 | wb = Workbook() 9 | 10 | # 활성화된 엑셀 시트를 선택합니다. 11 | ws = wb.active 12 | 13 | # 엑셀 제목을 지정합니다. 14 | ws.title = "output" 15 | 16 | 17 | # 데이터베이스 연결 문자열을 세팅 합니다. 18 | server = 'localhost' 19 | database = 'mytest' 20 | username = 'pyuser' 21 | password = 'test1234' 22 | 23 | # 데이터 베이스에 연결 합니다. 24 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 25 | 26 | # 커서를 만듭니다. 27 | cursor = cnxn.cursor() 28 | 29 | 30 | ### 칼럼 이름 저장하기 31 | # supermarket 의 칼럼들을 가져옵니다. 32 | cursor.execute('SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = \'supermarket\';') 33 | 34 | # 첫 번째 칼럼을 나타냅니다. 35 | column_char = 'a' 36 | 37 | # 한 행씩 가져오면서, 38 | row = cursor.fetchone() 39 | while row: 40 | # 칼럼 문자를 하나씩 증가하면서 A1~E1에 조회해 온 칼럼 명을 넣습니다. 41 | ws[column_char + '1'] = row[0] 42 | column_char = chr(ord(column_char) + 1) 43 | row = cursor.fetchone() 44 | 45 | 46 | ### 테이블 내용 저장 하기 47 | # supermarket 테이블의 내용을 가져옵니다. 48 | cursor.execute('SELECT Itemno, Category, FoodName, Company, Price FROM supermarket(nolock);') 49 | 50 | # 2번째 행을 나타냅니다. 51 | row_num = 2 52 | 53 | # 한 행씩 가져오면서, 54 | row = cursor.fetchone() 55 | while row: 56 | # 예전 수동 타자기 처럼, 새로운 줄이 오게 되면, 첫째 열인 A 로 돌아가는 초기 값 입니다. 57 | column_char = 'a' 58 | 59 | # 1~5 까지 x 가 변하면서 칼럼 문자, row를 하나씩 늘여 결과를 하나씩 담습니다. 60 | # ws['a1'] = row[0], ws['b1'] = row[1], ws['c1'] = row[2]... 61 | for x in range(1, 6): 62 | ws[column_char + str(row_num)] = row[x-1] 63 | column_char = chr(ord(column_char) + 1) 64 | 65 | # 다음 행을 표시하기 위해 뒤의 숫자를 증가 시킵니다. 66 | row_num = row_num + 1 67 | row = cursor.fetchone() 68 | 69 | 70 | # 파일을 실제 저장 합니다. 71 | wb.save("result.xlsx") 72 | 73 | print("엑셀저장 완료") 74 | -------------------------------------------------------------------------------- /예제 소스 코드/07교시/excel_from_database_by_number.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | from openpyxl import load_workbook 3 | # 모듈 호환 에러가 나서 주석 처리 합니다. 4 | #from openpyxl.compat import range 5 | import pyodbc 6 | 7 | # 워크북을 하나 만듭니다. 8 | wb = Workbook() 9 | 10 | # 활성화된 엑셀 시트를 선택합니다. 11 | ws = wb.active 12 | 13 | # 엑셀 제목을 지정합니다. 14 | ws.title = "output" 15 | 16 | 17 | # 데이터베이스 연결 문자열을 세팅 합니다. 18 | server = 'localhost' 19 | database = 'mytest' 20 | username = 'pyuser' 21 | password = 'test1234' 22 | 23 | # 데이터 베이스에 연결 합니다. 24 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 25 | 26 | # 커서를 만듭니다. 27 | cursor = cnxn.cursor() 28 | 29 | 30 | ### 칼럼 이름 저장하기 31 | # supermarket 의 칼럼들을 가져옵니다. 32 | cursor.execute('SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = \'supermarket\';') 33 | 34 | # 첫 번째 칼럼을 나타냅니다. 35 | column_num = 1 36 | 37 | # 한 행 씩 가져오면서, 38 | row = cursor.fetchone() 39 | while row: 40 | # 칼럼 문자를 하나씩 증가하면서 A1~E1에 조회해 온 칼럼 명을 넣습니다 41 | ws.cell(row = 1, column = column_num).value = row[0] 42 | column_num = column_num + 1 43 | row = cursor.fetchone() 44 | 45 | 46 | ### 테이블 내용 저장 하기 47 | # supermarket 테이블의 내용을 가져옵니다. 48 | cursor.execute('SELECT Itemno, Category, FoodName, Company, Price FROM supermarket(nolock);') 49 | 50 | # 2번째 행을 나타냅니다. 51 | row_num = 2 52 | 53 | 54 | # 한 행씩 가져오면서, 55 | row = cursor.fetchone() 56 | while row: 57 | # 예전 수동 타자기 처럼, 새로운 줄이 오게 되면, 첫째 셀 1 로 돌아가는 초기 값 입니다. 58 | column_num = 1 59 | 60 | # 1~5 까지 x 가 변하면서 칼럼 번호, row를 하나씩 늘여 결과를 하나씩 담습니다. 61 | for x in range(1, 6): 62 | ws.cell(row = row_num, column = column_num).value = row[x-1] 63 | column_num = column_num + 1 64 | 65 | # 다음 행을 표시하기 위해 뒤의 숫자를 증가합니다. 66 | row_num = row_num + 1 67 | row = cursor.fetchone() 68 | 69 | 70 | # 파일을 실제 저장 합니다. 71 | wb.save("result.xlsx") 72 | 73 | print("엑셀저장 완료") 74 | -------------------------------------------------------------------------------- /예제 소스 코드/07교시/excel_read.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | from openpyxl import load_workbook 3 | # 모듈 호환 에러가 나서 주석 처리 합니다. 4 | #from openpyxl.compat import range 5 | 6 | # 엑셀을 읽어 옵니다. 7 | wb_read = load_workbook(filename = 'result.xlsx') 8 | 9 | # 이름이 output 인 sheet 를 가져옵니다. 10 | my_sheet = wb_read['output'] 11 | 12 | # A1, B2 값을 출력합니다. 13 | print ("A1 : " + my_sheet['A1'].value) 14 | print ("B2 : " + my_sheet['B2'].value) 15 | -------------------------------------------------------------------------------- /예제 소스 코드/07교시/excel_sample.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | import datetime 3 | 4 | # 워크북을 하나 만듭니다. 5 | wb = Workbook() 6 | 7 | # 활성 워크시트를 선택 합니다(첫 번째 시트가 선택 됩니다). 8 | ws = wb.active 9 | 10 | # A1 행에 42라는 숫자를 넣습니다. 11 | ws['A1'] = 42 12 | 13 | # 현재 글자가 쓰여있는 다음 row 에 1,2,3 이라고 넣습니다. 14 | ws.append([1, 2, 3]) 15 | 16 | # 셀이 겹치는 부분을 수정 했습니다. 17 | ws['A3'] = datetime.datetime.now() 18 | 19 | # 메모리에 있는 워크 북을 실제 물리적인 엑셀 파일로 저장한다. 20 | wb.save("sample.xlsx") 21 | 22 | print("엑셀저장 완료") -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg.txt: -------------------------------------------------------------------------------- 1 | test 2 | me 3 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg2.txt: -------------------------------------------------------------------------------- 1 | 1cake - Right 2 | jelly 12hey - Wrong 3 | maybe12 - Wrong 4 | 3joy - Wrong 5 | 4432 - Right 6 | 23b - Right 7 | 5555b - Wrong 8 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg_sample1.py: -------------------------------------------------------------------------------- 1 | # regular expression 모듈을 불러 옵니다. 2 | import re 3 | 4 | # 정규표현식 패턴을 등록합니다(처음 시작이 < 이고 > 로 닫히는 단어). 5 | pattern = re.compile("^<.*>") 6 | 7 | # reg.txt 파일을 한줄 한줄 가져와서(enumerate) 루프를 돌리면서, 8 | for i, line in enumerate(open('reg.txt')): 9 | # 해당 줄에서 원하는 패턴을 모두 찾아 한건 한 건 꺼내어서, 10 | for match in re.finditer(pattern, line): 11 | # 찾은 값을 출력합니다. 12 | print (match.groups()) 13 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg_sample2.py: -------------------------------------------------------------------------------- 1 | # regular expression 모듈을 불러 옵니다. 2 | import re 3 | 4 | # 정규표현식 패턴을 등록합니다(처음 시작이 < 이고 > 로 닫히는 단어). 5 | pattern = re.compile("^<.*>") 6 | 7 | # reg.txt 파일을 한줄 한줄 가져와서(enumerate) 루프를 돌리면서, 8 | for i, line in enumerate(open('reg.txt')): 9 | # 해당 줄에서 원하는 패턴을 모두 찾아 한건 한 건 꺼내어서, 10 | for match in re.finditer(pattern, line): 11 | # 찾은 값을 출력합니다. 12 | print (match.group()) 13 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg_sample3.py: -------------------------------------------------------------------------------- 1 | # regular expression 모듈을 불러 옵니다. 2 | import re 3 | 4 | # 정규표현식 패턴을 등록합니다(처음 시작이 < 이고 > 로 닫히는 단어). 5 | # 패턴을 괄호로 감쌉니다. 6 | pattern = re.compile("(^<.*>)") 7 | 8 | # reg.txt 파일을 한줄 한줄 가져와서(enumerate) 루프를 돌리면서, 9 | for i, line in enumerate(open('reg.txt')): 10 | # 해당 줄에서 원하는 패턴을 모두 찾아 한건 한 건 꺼내어서, 11 | for match in re.finditer(pattern, line): 12 | # 찾은 값을 출력합니다. 13 | print (match.groups()) 14 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg_sample4.py: -------------------------------------------------------------------------------- 1 | # regular expression 모듈을 불러 옵니다. 2 | import re 3 | 4 | # 정규표현식 패턴을 등록합니다(처음 시작이 < 이고 > 로 닫히는 단어). 5 | # 원하는 부분을 괄호로 감쌉니다. 6 | pattern = re.compile("^<(.*)>") 7 | 8 | # reg.txt 파일을 한줄 한줄 가져와서(enumerate) 루프를 돌리면서, 9 | for i, line in enumerate(open('reg.txt')): 10 | # 해당 줄에서 원하는 패턴을 모두 찾아 한건 한 건 꺼내어서, 11 | for match in re.finditer(pattern, line): 12 | # 찾은 값을 출력합니다. 13 | # 전체 그룹에서 1번 그룹을 가져오도록 변경 14 | print (match.group(1)) 15 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/reg_sample5.py: -------------------------------------------------------------------------------- 1 | # regular expression 모듈을 불러 옵니다. 2 | import re 3 | 4 | # 정규표현식 패턴 등록(처음 시작이 < 이고 > 로 닫히는 단어) 5 | pattern = re.compile("^[0-9]+.*") 6 | 7 | # reg.txt 파일을 한줄 한줄 가져와서(enumerate) 루프를 돌리면서, 8 | for i, line in enumerate(open('reg2.txt')): 9 | # 해당 줄에서 원하는 패턴을 모두 찾아 한건 한 건 꺼내어서, 10 | for match in re.finditer(pattern, line): 11 | # 찾은 값을 출력합니다. 12 | print (match.group()) 13 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/미니문법/dictionary_sample.py: -------------------------------------------------------------------------------- 1 | my_dict = {'boy':'a young man', 'girl': 'a young women'} 2 | print (my_dict['boy']) 3 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/미니문법/list_sample.py: -------------------------------------------------------------------------------- 1 | mylist = [1, 2, 3] 2 | mylist.append("four") 3 | mylist.reverse() 4 | 5 | for i in mylist: 6 | print(i) 7 | -------------------------------------------------------------------------------- /예제 소스 코드/08교시/미니문법/tuple_sample.py: -------------------------------------------------------------------------------- 1 | mytuple = (1, 3, 2, 3) 2 | mycount = mytuple.count(3) 3 | print (mycount) 4 | -------------------------------------------------------------------------------- /예제 소스 코드/09교시/wx_encryption.py: -------------------------------------------------------------------------------- 1 | import wx 2 | import base64 3 | from Crypto import Random 4 | from Crypto.Cipher import AES 5 | import hashlib 6 | 7 | # 암호화 관련 초기화 코드 입니다. 8 | BS = 16 9 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode() 10 | unpad = lambda s : s[0:-s[-1]] 11 | 12 | 13 | # 윈도우즈 정의 클래스 입니다. 14 | class Frame(wx.Frame): 15 | def __init__(self, parent, title): 16 | wx.Frame.__init__(self, parent, title=title, size=(500, 200)) 17 | self.panel = wx.Panel(self) 18 | self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) 19 | 20 | # 버튼을 생성 합니다. 21 | self.btn = wx.Button(self.panel, -1, '암호화') 22 | 23 | # 텍스트 박스를 생성합니다. 24 | self.txt = wx.TextCtrl(self.panel, -1, size=(140,-1)) 25 | self.txt.SetValue('input your value') 26 | 27 | # 텍스트 라벨을 생성합니다. 28 | self.some_text = wx.StaticText(self.panel, size=(140,150), pos=(10,60)) 29 | self.some_text.SetLabel('result is...') 30 | 31 | # 버튼 클릭 시 이벤트를 연결 합니다. 32 | self.Bind(wx.EVT_BUTTON, self.GetEncryption, self.btn) 33 | 34 | sizer = wx.BoxSizer(wx.VERTICAL) 35 | sizer.Add(self.btn) 36 | sizer.Add(self.txt) 37 | 38 | self.panel.SetSizer(sizer) 39 | self.Show() 40 | 41 | # 버튼 클릭 시 실행 되어, 암호화 하는 함수 입니다. 42 | def GetEncryption(self, e): 43 | # 텍스트 박스(self.txt)로 부터 값을 얻어와 암호화 함수로 넘겨 줍니다. 44 | cipher = AESCipher('mysecretpassword') 45 | self.enc = cipher.encrypt(self.txt.GetValue()) 46 | 47 | # 받은 값을 텍스트 라벨에 출력합니다. 48 | self.some_text.SetLabel(self.enc) 49 | 50 | 51 | def OnCloseWindow(self, e): 52 | self.Destroy() 53 | 54 | 55 | # 암호화 관련 클래스 입니다. 56 | class AESCipher: 57 | 58 | def __init__( self, key ): 59 | self.key = hashlib.sha256(key.encode()).digest() 60 | 61 | def encrypt( self, raw ): 62 | raw = raw.encode() 63 | raw = pad(raw) 64 | iv = Random.new().read( AES.block_size ) 65 | cipher = AES.new( self.key, AES.MODE_CBC, iv ) 66 | return base64.b64encode( iv + cipher.encrypt( raw ) ).decode() 67 | 68 | def decrypt( self, enc ): 69 | enc = base64.b64decode(enc) 70 | iv = enc[:16] 71 | cipher = AES.new(self.key, AES.MODE_CBC, iv ) 72 | return unpad(cipher.decrypt( enc[16:] )).decode() 73 | 74 | # 메인코드 입니다. 75 | # 윈도우를 띄우고 제목을 넣습니다. 76 | app = wx.App() 77 | frame = Frame(None, 'WxEncryption') 78 | app.MainLoop() 79 | -------------------------------------------------------------------------------- /예제 소스 코드/09교시/미니문법/class_sample.py: -------------------------------------------------------------------------------- 1 | # 직업 클래스 2 | class Character: 3 | def __init__(self, job): 4 | self.job_class = job 5 | 6 | def fireball(self): 7 | if self.job_class == "magician": 8 | print("fireball >> ***") 9 | else: 10 | print("I can't do it") 11 | 12 | # 마법사 만들기 13 | new_character = Character("magician") 14 | # 파이어볼 쏘기 15 | new_character.fireball() 16 | 17 | # 도둑 만들기 18 | new_character2 = Character("theif") 19 | # 파이어볼 쏘기 20 | new_character2.fireball() -------------------------------------------------------------------------------- /예제 소스 코드/10교시/ip.txt: -------------------------------------------------------------------------------- 1 | 202.30.50.51 2 | 103.235.46.39 3 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/whois_iptest.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | 4 | # 요청 세션을 하나 만듭니다. 5 | s = requests.session() 6 | 7 | # API 를 호출합니다. 8 | con = s.get('http://whois.kisa.or.kr/openapi/whois.jsp?query=202.30.50.51&key=발급받은키&answer=json') 9 | 10 | # 호출 받은 API 결과를 json 형태로 받습니다. 11 | json_data = json.loads(con.text) 12 | 13 | # 결과를 저장할 빈 리스트 생성합니다. 14 | WhoIsData = [] 15 | 16 | # 피들러에서 파악했던 값들을 하나씩 추출해 리스트에 담습니다. 17 | WhoIsData.append(json_data['whois']['query']) 18 | WhoIsData.append(json_data['whois']['countryCode']) 19 | WhoIsData.append(json_data['whois']['korean']['PI']['netinfo']['addr']) 20 | WhoIsData.append(json_data['whois']['korean']['PI']['netinfo']['range']) 21 | WhoIsData.append(json_data['whois']['korean']['PI']['netinfo']['servName']) 22 | 23 | # 리스트를 출력 합니다. 24 | print(WhoIsData) 25 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/whoisapi_1st.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | from openpyxl import Workbook 4 | from openpyxl import load_workbook 5 | # 모듈 호환 에러가 나서 주석 처리 합니다. 6 | #from openpyxl.compat import range 7 | 8 | # 워크북을 하나 만듭니다. 9 | wb = Workbook() 10 | 11 | # 활성화된 엑셀 시트를 선택합니다. 12 | ws = wb.active 13 | 14 | # 엑셀 제목을 지정합니다. 15 | ws.title = "whois ip info" 16 | 17 | # 각 IP 의 조회 결과를 엑셀에 넣을 때 사용한 전역 변수 입니다. 18 | row_num = 2 19 | 20 | 21 | # 제일 위쪽의 제목 줄을 저장하는 함수 입니다. 22 | def save_field(field_list): 23 | # 컬럼 초기화 값 24 | column_char = 'a' 25 | 26 | # 리스트의 내용들을 가져와서 엑셀 맨 첫 줄에 저장합니다. 27 | for field in field_list: 28 | ws[column_char + '1'] = field 29 | column_char = chr(ord(column_char) + 1) 30 | 31 | 32 | # 엑셀에 조회결과를 저장하는 함수 입니다. 33 | def save_content(address_list): 34 | # 컬럼 초기화 값 35 | column_char = 'a' 36 | 37 | # 엑셀 두 번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 38 | global row_num 39 | 40 | # 리스트의 내용을 가져와서 row_num 을 기준으로 저장 합니다. 41 | for address in address_list: 42 | ws[column_char + str(row_num)] = address 43 | column_char = chr(ord(column_char) + 1) 44 | 45 | 46 | 47 | 48 | 49 | # IP 하나에 대해 WHOIS API 를 호출하는 함수 입니다. 50 | def requestWhois(searchIP): 51 | # 엑셀 2번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 52 | global row_num 53 | 54 | # 결과를 담을 배열을 초기화 합니다. 55 | whois_data = [] 56 | 57 | # API 를 호출 합니다(발급받은키는 독자분의 키로 수정해야 합니다) 58 | con = s.get('http://whois.kisa.or.kr/openapi/whois.jsp?query=' + searchIP + '&key=발급받은키&answer=json') 59 | 60 | # 호출된 결과를 json 형태로 파싱하여 가져옵니다. 61 | json_data = json.loads(con.text) 62 | 63 | # 각 결과 값을 리스트에 추가 합니다. 64 | whois_data.append(json_data['whois']['query']) 65 | whois_data.append(json_data['whois']['countryCode']) 66 | 67 | # 각 결과 값을 배열에 저장 68 | whois_data.append(json_data['whois']['query']) 69 | whois_data.append(json_data['whois']['countryCode']) 70 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['addr']) 71 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['range']) 72 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['servName']) 73 | 74 | # 결과를 로그 용으로 화면에 뿌립니다. 75 | print(whois_data) 76 | 77 | # 엑셀에 결과를 저장합니다. 78 | save_content(whois_data) 79 | row_num = row_num + 1 80 | 81 | 82 | # 엑셀 첫 째 줄에 각 필드들의 제목을 저장합니다. 83 | excel_fields = ['IP', 'countryCode', 'addr', 'IP_range', 'servName'] 84 | save_field(excel_fields) 85 | 86 | # IP 가 담긴 텍스트 파일을 열어 줄로 나눠서 리스트에 담습니다. 87 | f = open('ip.txt', 'r') 88 | iplist = f.read().splitlines() 89 | 90 | # 텍스트 파일을 닫습니다. 91 | f.close() 92 | 93 | # API 를 호출할 세션을 생성합니다. 94 | s = requests.session() 95 | 96 | # IP 별로 조회하여 엑셀에 저장합니다. 97 | for ip in iplist: 98 | requestWhois(ip) 99 | 100 | # 파일을 실제 저장 합니다. 101 | wb.save("ipinfo.xlsx") 102 | 103 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/whoisapi_2nd.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | from openpyxl import Workbook 4 | from openpyxl import load_workbook 5 | # 모듈 호환 에러가 나서 주석 처리 합니다. 6 | #from openpyxl.compat import range 7 | 8 | # 워크북을 하나 만듭니다. 9 | wb = Workbook() 10 | 11 | # 활성화된 엑셀 시트를 선택합니다. 12 | ws = wb.active 13 | 14 | # 엑셀 제목을 지정합니다. 15 | ws.title = "whois ip info" 16 | 17 | # 각 IP 의 조회 결과를 엑셀에 넣을 때 사용한 전역 변수 입니다. 18 | row_num = 2 19 | 20 | 21 | # 제일 위쪽의 제목 줄을 저장하는 함수 입니다. 22 | def save_field(field_list): 23 | # 컬럼 초기화 값 24 | column_char = 'a' 25 | 26 | # 리스트의 내용들을 가져와서 엑셀 맨 첫 줄에 저장합니다. 27 | for field in field_list: 28 | ws[column_char + '1'] = field 29 | column_char = chr(ord(column_char) + 1) 30 | 31 | 32 | # 엑셀에 조회결과를 저장하는 함수 입니다. 33 | def save_content(address_list): 34 | # 컬럼 초기화 값 35 | column_char = 'a' 36 | 37 | # 엑셀 두 번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 38 | global row_num 39 | 40 | # 리스트의 내용을 가져와서 row_num 을 기준으로 저장 합니다. 41 | for address in address_list: 42 | ws[column_char + str(row_num)] = address 43 | column_char = chr(ord(column_char) + 1) 44 | 45 | 46 | 47 | 48 | 49 | # IP 하나에 대해 WHOIS API 를 호출하는 함수 입니다. 50 | def requestWhois(searchIP): 51 | # 엑셀 2번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 52 | global row_num 53 | 54 | # 결과를 담을 배열을 초기화 합니다. 55 | whois_data = [] 56 | 57 | # API 를 호출 합니다(발급받은키는 독자분의 키로 수정해야 합니다) 58 | con = s.get('http://whois.kisa.or.kr/openapi/whois.jsp?query=' + searchIP + '&key=발급받은키&answer=json') 59 | 60 | # 호출된 결과를 json 형태로 파싱하여 가져옵니다. 61 | json_data = json.loads(con.text) 62 | 63 | # 각 결과 값을 리스트에 추가 합니다. 64 | whois_data.append(json_data['whois']['query']) 65 | whois_data.append(json_data['whois']['countryCode']) 66 | 67 | # 해당 값들이 없어 에러처리가 나면 무시 합니다. 68 | try: 69 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['addr']) 70 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['range']) 71 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['servName']) 72 | except: 73 | pass 74 | 75 | # 해당 값들이 없어 에러처리가 나면 무시 합니다. 76 | try: 77 | whois_data.append(json_data['whois']['korean']['ISP']['netinfo']['addr']) 78 | whois_data.append(json_data['whois']['korean']['ISP']['netinfo']['range']) 79 | whois_data.append(json_data['whois']['korean']['ISP']['netinfo']['servName']) 80 | except: 81 | pass 82 | 83 | # 결과를 로그 용으로 화면에 뿌립니다. 84 | print(whois_data) 85 | 86 | # 엑셀에 결과를 저장합니다. 87 | save_content(whois_data) 88 | row_num = row_num + 1 89 | 90 | 91 | # 엑셀 첫 째 줄에 각 필드들의 제목을 저장합니다. 92 | excel_fields = ['IP', 'countryCode', 'addr', 'IP_range', 'servName'] 93 | save_field(excel_fields) 94 | 95 | # IP 가 담긴 텍스트 파일을 열어 줄로 나눠서 리스트에 담습니다. 96 | f = open('ip.txt', 'r') 97 | iplist = f.read().splitlines() 98 | 99 | # 텍스트 파일을 닫습니다. 100 | f.close() 101 | 102 | # API 를 호출할 세션을 생성합니다. 103 | s = requests.session() 104 | 105 | # IP 별로 조회하여 엑셀에 저장합니다. 106 | for ip in iplist: 107 | requestWhois(ip) 108 | 109 | # 파일을 실제 저장 합니다. 110 | wb.save("ipinfo.xlsx") -------------------------------------------------------------------------------- /예제 소스 코드/10교시/whoisapi_3rd.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | from openpyxl import Workbook 4 | from openpyxl import load_workbook 5 | # 모듈 호환 에러가 나서 주석 처리 합니다. 6 | #from openpyxl.compat import range 7 | 8 | # 워크북을 하나 만듭니다. 9 | wb = Workbook() 10 | 11 | # 활성화된 엑셀 시트를 선택합니다. 12 | ws = wb.active 13 | 14 | # 엑셀 제목을 지정합니다. 15 | ws.title = "whois ip info" 16 | 17 | # 각 IP 의 조회 결과를 엑셀에 넣을 때 사용한 전역 변수 입니다. 18 | row_num = 2 19 | 20 | 21 | # 제일 위쪽의 제목 줄을 저장하는 함수 입니다. 22 | def save_field(field_list): 23 | # 컬럼 초기화 값 24 | column_char = 'a' 25 | 26 | # 리스트의 내용들을 가져와서 엑셀 맨 첫 줄에 저장합니다. 27 | for field in field_list: 28 | ws[column_char + '1'] = field 29 | column_char = chr(ord(column_char) + 1) 30 | 31 | 32 | # 엑셀에 조회결과를 저장하는 함수 입니다. 33 | def save_content(address_list): 34 | # 컬럼 초기화 값 35 | column_char = 'a' 36 | 37 | # 엑셀 두 번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 38 | global row_num 39 | 40 | # 리스트의 내용을 가져와서 row_num 을 기준으로 저장 합니다. 41 | for address in address_list: 42 | ws[column_char + str(row_num)] = address 43 | column_char = chr(ord(column_char) + 1) 44 | 45 | 46 | 47 | 48 | 49 | # IP 하나에 대해 WHOIS API 를 호출하는 함수 입니다. 50 | def requestWhois(searchIP): 51 | # 엑셀 2번째 줄부터 IP정보를 이어서 저장하기 위해서 전역 변수를 가져옵니다. 52 | global row_num 53 | 54 | # 결과를 담을 배열을 초기화 합니다. 55 | whois_data = [] 56 | 57 | # API 를 호출 합니다(발급받은키는 독자분의 키로 수정해야 합니다) 58 | con = s.get('http://whois.kisa.or.kr/openapi/whois.jsp?query=' + searchIP + '&key=발급받은키&answer=json') 59 | 60 | # 호출된 결과를 json 형태로 파싱하여 가져옵니다. 61 | json_data = json.loads(con.text) 62 | 63 | # 각 결과 값을 리스트에 추가 합니다. 64 | whois_data.append(json_data['whois']['query']) 65 | whois_data.append(json_data['whois']['countryCode']) 66 | 67 | # json 인자가 있는지 체크하는 식으로 에러처리 바꿈 68 | if 'korean' in json_data['whois']: 69 | if 'PI' in json_data['whois']['korean']: 70 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['addr']) 71 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['range']) 72 | whois_data.append(json_data['whois']['korean']['PI']['netinfo']['servName']) 73 | elif 'ISP' in json_data['whois']['korean']: 74 | whois_data.append(json_data['whois']['korean']['ISP']['netinfo']['addr']) 75 | whois_data.append(json_data['whois']['korean']['ISP']['netinfo']['range']) 76 | 77 | # 결과를 로그 용으로 화면에 뿌립니다. 78 | print(whois_data) 79 | 80 | # 엑셀에 결과를 저장합니다. 81 | save_content(whois_data) 82 | row_num = row_num + 1 83 | 84 | 85 | # 엑셀 첫 째 줄에 각 필드들의 제목을 저장합니다. 86 | excel_fields = ['IP', 'countryCode', 'addr', 'IP_range', 'servName'] 87 | save_field(excel_fields) 88 | 89 | # IP 가 담긴 텍스트 파일을 열어 줄로 나눠서 리스트에 담습니다. 90 | f = open('ip.txt', 'r') 91 | iplist = f.read().splitlines() 92 | 93 | # 텍스트 파일을 닫습니다. 94 | f.close() 95 | 96 | # API 를 호출할 세션을 생성합니다. 97 | s = requests.session() 98 | 99 | # IP 별로 조회하여 엑셀에 저장합니다. 100 | for ip in iplist: 101 | requestWhois(ip) 102 | 103 | # 파일을 실제 저장 합니다. 104 | wb.save("ipinfo.xlsx") -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/except_sample.py: -------------------------------------------------------------------------------- 1 | try: 2 | f = open('noname.txt', 'r') 3 | except OSError: 4 | pass 5 | finally: 6 | print('cannot open the file') 7 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/file_readlines.py: -------------------------------------------------------------------------------- 1 | f = open('ip.txt', 'r') 2 | iplist = f.readlines() 3 | 4 | for ip in iplist: 5 | print(ip) 6 | f.close() -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/file_write.py: -------------------------------------------------------------------------------- 1 | f = open('write.txt', 'w') 2 | f.write('hello') 3 | f.close() 4 | print('write done') -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/global_variable.py: -------------------------------------------------------------------------------- 1 | # 정의 없이 사용합니다. 2 | def print_global(): 3 | print(a) 4 | 5 | # global 로 정의해 사용합니다. 6 | def print_global2(): 7 | global a 8 | print(a) 9 | 10 | # 함수안에 같은 이름의 변수를 만듭니다. 11 | def print_local(): 12 | a = "local a" 13 | print(a) 14 | 15 | # 글로벌 변수로 간주 될 변수 입니다. 16 | a = "global a" 17 | 18 | print_global() 19 | print_global2() 20 | print_local() 21 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/ip.txt: -------------------------------------------------------------------------------- 1 | 202.30.50.51 2 | 103.235.46.39 3 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/json_dumps.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | # 리스트 데이터를 JSON 데이터로 변환합니다. 4 | my_list = ["cat", "dog", "pig"] 5 | to_json = json.dumps(my_list) 6 | 7 | # 변수 타입과 내용 출력합니다. 8 | print(type(to_json)) 9 | print(to_json) 10 | -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/json_loads.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | # 딕셔너리 형태의 JSON 데이터를 읽어옵니다. 4 | my_json = '{"cat": 3, "dog": 10, "pig": 2}' 5 | to_dictionary = json.loads(my_json) 6 | 7 | # 리스트 형태의 JSON 데이터를 읽어옵니다. 8 | my_json2 = '["cat", "dog", "pig"]' 9 | to_list = json.loads(my_json2) 10 | 11 | # 변수 타입과 내용 출력합니다. 12 | print(type(to_dictionary)) 13 | print(to_dictionary['cat']) 14 | 15 | # 변수 타입과 내용 출력합니다. 16 | print(type(to_list)) 17 | print(to_list[0]) -------------------------------------------------------------------------------- /예제 소스 코드/10교시/미니문법/with_sample.py: -------------------------------------------------------------------------------- 1 | with open('write.txt', 'w') as f: 2 | f.write('hello') 3 | print('write done') -------------------------------------------------------------------------------- /예제 소스 코드/11교시/beautiful.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | 3 | # 샘플 HTML 문서 데이터를 만듭니다. 4 | html_doc = """ 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
초콜릿과자
사탕오렌지
15 | """ 16 | 17 | # html 파서를 이용해서 html 형태의 데이터를 읽어옵니다. 18 | soup = BeautifulSoup(html_doc, 'html.parser') 19 | 20 | # 1) td 태그를 모두 찾아서 td_list 에 담은 후, 루프를 돌리면서 각 td 태그 내용을 출력합니다. 21 | td_list = soup.find_all('td') 22 | for td_item in td_list: 23 | print(td_item.string) 24 | 25 | # 구분을 위해 빈 줄을 출력 합니다. 26 | print ('\n') 27 | 28 | # 2) id 가 choco 인 항목을 찾아서 해당 태그 내용을 출력합니다. 29 | id_list = soup.find(id='choco') 30 | print(id_list.string) 31 | 32 | 33 | # 3) td 태그이면서 name 속성이 candy 인 항목('캔디')을 찾아서, 34 | # 그 다음에 있는 같은 td 속성을 찾아서 태그 내용을('오렌지') 출력합니다. 35 | td_list = soup.find('td', {'name':'candy'}) 36 | print(td_list.find_next_sibling().string) 37 | 38 | print ('\n') 39 | 40 | # 4) 앞의 2번과 동일하지만 css selector 방식으로 사용합니다. 41 | td_list = soup.select('#choco') 42 | print(td_list[0].string) 43 | 44 | # 5) 앞의 3번과 동일하지만 css selector 방식으로 사용합니다. 45 | td_list = soup.select('td[name="candy"]') 46 | print(td_list[0].find_next_sibling().string) -------------------------------------------------------------------------------- /예제 소스 코드/11교시/whois_call_jscfile.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import re 3 | 4 | # jsc 페이지를 post 로 호출합니다. 5 | payload = {'query': '202.30.50.51', 'ip': '1.225.79.26'} 6 | r = requests.post("https://whois.kisa.or.kr/kor/whois.jsc", data=payload) 7 | 8 | # 받아온 페이지의 인코딩을 지정 합니다. 9 | r.encoding = 'utf-8' 10 | # print(r.text) 11 | 12 | 13 | # 정규표현식을 이용해 결과에서 주소를 얻어옵니다. 14 | pattern = re.compile("주소.*: ([^0-9].*)") 15 | match = re.findall(pattern, r.text) 16 | print (match[0]) 17 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_1st.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.keys import Keys 3 | 4 | # Firefox 웹 드라이버를 생성 합니다. 5 | driver = webdriver.Firefox() 6 | 7 | # 구글 페이지를 호출해 가져옵니다. 8 | driver.get("https://www.google.com") 9 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_2nd.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.keys import Keys 3 | 4 | # Firefox 웹 드라이버를 생성 합니다. 5 | driver = webdriver.Firefox() 6 | 7 | # 구글 페이지에서 "파이썬 공부" 라고 검색해 옵니다. 8 | driver.get("https://www.google.com/search?q=파이썬 공부") 9 | 10 | # 검색 된 div 태그 안에 들은 링크 들을 가져옵니다. 11 | results = driver.find_elements_by_css_selector('div.g') 12 | 13 | # 그 중 첫번째 링크 안에서 a 태그를 찾습니다. 14 | link = results[0].find_element_by_tag_name("a") 15 | 16 | # a 태그 안에서 href 이라는 속성을 가져옵니다. 17 | href = link.get_attribute("href") 18 | 19 | # 속성 안에서 q 에 해당되는 값을 가져옵니다. 20 | import urlparse 21 | print(urlparse.parse_qs(urlparse.urlparse(href).query)["url"]) 22 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_3rd.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.keys import Keys 3 | 4 | # Firefox 웹 드라이버를 생성 합니다. 5 | driver = webdriver.Firefox() 6 | 7 | # 구글 페이지에서 "파이썬 공부" 라고 검색해 옵니다. 8 | driver.get("https://www.google.com/search?q=파이썬 공부") 9 | 10 | # 검색 된 div 태그 안에 들은 링크 들을 가져옵니다. 11 | results = driver.find_elements_by_css_selector('div.g') 12 | 13 | # 그 중 첫번째 링크 안에서 a 태그를 찾습니다. 14 | link = results[0].find_element_by_tag_name("a") 15 | 16 | # a 태그 안에서 href 이라는 속성을 가져옵니다. 17 | href = link.get_attribute("href") 18 | 19 | # 속성 안에서 q 에 해당되는 값을 가져옵니다. 20 | from furl import furl 21 | f = furl(href) 22 | print (f.args['url']) 23 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_4th.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.keys import Keys 3 | 4 | # Firefox 웹 드라이버를 생성 합니다. 5 | driver = webdriver.Firefox() 6 | 7 | # 구글 페이지에서 "파이썬 공부" 라고 검색해 옵니다. 8 | driver.get("https://www.google.com/search?q=파이썬 공부") 9 | 10 | # 검색 된 div 태그 안에 들은 링크 들을 가져옵니다. 11 | results = driver.find_elements_by_css_selector('div.g') 12 | 13 | # 그 중 첫번째 링크 안에서 a 태그를 찾습니다. 14 | link = results[0].find_element_by_tag_name("a") 15 | 16 | # a 태그 안에서 href 이라는 속성을 가져옵니다. 17 | href = link.get_attribute("href") 18 | 19 | # 화면에 출력을 해봅니다. 20 | print(href) 21 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_firefox.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # Firefox 웹 드라이버를 생성 합니다. 4 | browser = webdriver.Firefox() 5 | 6 | # 구글 페이지에서 "파이썬 공부" 라고 검색해 옵니다. 7 | browser.get("https://www.google.com/search?q=파이썬 공부") 8 | 9 | # 검색 된 div 태그 안에 들은 링크 들을 가져옵니다. 10 | results = browser.find_elements_by_css_selector('div.g') 11 | 12 | # 인자를 담을 리스트를 만듭니다. 13 | hrefs = [] 14 | 15 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 16 | for i in range(0, 5): 17 | link = results[i].find_element_by_tag_name("a") 18 | hrefs.append(link.get_attribute("href")) 19 | 20 | # 화면에 출력해 봅니다. 21 | for href in hrefs: 22 | print(href) 23 | 24 | # 각 링크에 대해서 새 탭에서 엽니다. 25 | for href in hrefs: 26 | browser.execute_script('window.open("' + href + '","_blank");') 27 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_ie.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # IE 웹 드라이버를 로딩 합니다. 4 | browser = webdriver.Ie() 5 | 6 | # 구글에 "파이썬 공부" 검색어로 조회 합니다. 7 | browser.get("https://www.google.com") 8 | input_element = browser.find_element_by_name("q") 9 | input_element.send_keys("파이썬 공부") 10 | input_element.submit() 11 | 12 | # 대기 시간을 지정 합니다. 13 | import time 14 | time.sleep(5) 15 | 16 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 17 | results = browser.find_elements_by_css_selector('div.g') 18 | 19 | # 인자를 담을 리스트를 만듭니다. 20 | hrefs = [] 21 | 22 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 23 | for i in range(0, 5): 24 | link = results[i].find_element_by_tag_name("a") 25 | hrefs.append(link.get_attribute("href")) 26 | 27 | # 링크를 출력 해봅니다. 28 | for href in hrefs: 29 | print(href) 30 | 31 | # 링크들을 새 창에 띄웁니다. 32 | for href in hrefs: 33 | browser.execute_script('window.open("' + href + '","_blank");') -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_phantom_1st.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # firefox 웹 드라이버를 로드 합니다. 4 | browser = webdriver.PhantomJS() 5 | 6 | # 구글에 "파이썬 공부" 검색어로 조회 합니다. 7 | browser.get("https://www.google.com/search?q=파이썬 공부") 8 | 9 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 10 | results = browser.find_elements_by_css_selector('div.g') 11 | 12 | # 인자를 담을 리스트를 만듭니다. 13 | hrefs = [] 14 | 15 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 16 | for i in range(0, 5): 17 | link = results[i].find_element_by_tag_name("a") 18 | hrefs.append(link.get_attribute("href")) 19 | 20 | # 화면에 결과들을 출력 해봅니다. 21 | for href in hrefs: 22 | print(href) 23 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_phantom_2nd.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # firefox 웹 드라이버를 로드 합니다. 4 | # 실행 경로 수정 5 | phantomjs_path = r'c:\Python\phantomjs-2.1.1-windows\bin\phantomjs.exe' 6 | browser = webdriver.PhantomJS(phantomjs_path) 7 | 8 | # 구글에 "파이썬 공부" 검색어로 조회 합니다. 9 | browser.get("https://www.google.com/search?q=파이썬 공부") 10 | 11 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 12 | results = browser.find_elements_by_css_selector('div.g') 13 | 14 | # 인자를 담을 리스트를 만듭니다. 15 | hrefs = [] 16 | 17 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 18 | for i in range(0, 5): 19 | link = results[i].find_element_by_tag_name("a") 20 | hrefs.append(link.get_attribute("href")) 21 | 22 | # 화면에 결과들을 출력 해봅니다. 23 | for href in hrefs: 24 | print(href) 25 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_phantom_3rd.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # firefox 웹 드라이버를 로드 합니다. 4 | phantomjs_path = r'c:\Python\phantomjs-2.1.1-windows\bin\phantomjs.exe' 5 | browser = webdriver.PhantomJS(phantomjs_path) 6 | 7 | # 구글에 "파이썬 공부" 검색어로 조회 합니다. 8 | browser.get("https://www.google.com/search?q=파이썬 공부") 9 | 10 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 11 | results = browser.find_elements_by_css_selector('div.g') 12 | 13 | # 인자를 담을 리스트를 만듭니다. 14 | hrefs = [] 15 | 16 | # 디버그용 스크린 샷을 만듭니다. 17 | browser.save_screenshot('screen.png') 18 | 19 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 20 | for i in range(0, 5): 21 | link = results[i].find_element_by_tag_name("a") 22 | hrefs.append(link.get_attribute("href")) 23 | 24 | # 화면에 결과들을 출력 해봅니다. 25 | for href in hrefs: 26 | print(href) 27 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_phantom_4th.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # firefox 웹 드라이버를 로드 합니다. 4 | phantomjs_path = r'c:\Python\phantomjs-2.1.1-windows\bin\phantomjs.exe' 5 | browser = webdriver.PhantomJS(phantomjs_path) 6 | 7 | # 구글에 '파이썬 공부'로 검색어 조회합니다. 8 | browser.get("https://www.google.com") 9 | input_element = browser.find_element_by_name("q") 10 | input_element.send_keys("파이썬 공부") 11 | input_element.submit() 12 | 13 | 14 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 15 | results = browser.find_elements_by_css_selector('div.g') 16 | 17 | # 인자를 담을 리스트를 생성합니다. 18 | hrefs = [] 19 | 20 | # 디버그용 스크린 샷을 찍습니다. 21 | # browser.save_screenshot('screen.png') 22 | 23 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 24 | for i in range(0, 5): 25 | link = results[i].find_element_by_tag_name("a") 26 | hrefs.append(link.get_attribute("href")) 27 | 28 | # 화면에 그냥 프린트를 해봅니다. 29 | for href in hrefs: 30 | print(href) 31 | -------------------------------------------------------------------------------- /예제 소스 코드/12교시/selenium_phantom_final.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | # firefox 웹 드라이버를 로드 합니다. 4 | phantomjs_path = r'c:\Python\phantomjs-2.1.1-windows\bin\phantomjs.exe' 5 | browser = webdriver.PhantomJS(phantomjs_path) 6 | 7 | # 구글에 "파이썬 공부" 검색어로 조회 합니다. 8 | browser.get("https://www.google.com") 9 | input_element = browser.find_element_by_name("q") 10 | input_element.send_keys("파이썬 공부") 11 | input_element.submit() 12 | 13 | # 잠시 로딩될 시간을 기다립니다. 14 | import time 15 | time.sleep(2) 16 | 17 | # 결과 div 태그를 클래스 기준으로 검색해 다 가져옵니다. 18 | results = browser.find_elements_by_css_selector('div.g') 19 | 20 | # 인자를 담을 리스트를 만듭니다. 21 | hrefs = [] 22 | 23 | # 디버그용 스크린 샷을 만듭니다. 24 | # browser.save_screenshot('screen.png') 25 | 26 | # div 중 최초 5개를 가져와서, 그 안에서 a 태그를 찾고, a 태그 안의 href 속성을 찾습니다. 27 | for i in range(0, 5): 28 | link = results[i].find_element_by_tag_name("a") 29 | hrefs.append(link.get_attribute("href")) 30 | 31 | # href 에서 q 인자를 추출해 옵니다. 32 | from furl import furl 33 | for href in hrefs: 34 | f = furl(href) 35 | print (f.args['q']) 36 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/naver_upload.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | import pywinauto 3 | 4 | # 열려진 다이얼로그 창에 연결 합니다. 5 | app = pywinauto.application.Application() 6 | app.Connect(title="업로드할 파일 선택") 7 | 8 | # 다이얼로그 창을 정의 합니다. 9 | mainWindow = app['업로드할 파일 선택'] # main windows' title 10 | 11 | # 파일 이름 입력하는 창에가서 'test.txt' 라고 입력합니다. 12 | ctrl=mainWindow['Edit'] 13 | mainWindow.SetFocus() 14 | ctrl.ClickInput() 15 | ctrl.TypeKeys("test.txt") 16 | 17 | # 열기 버튼을 클릭합니다. 18 | mainWindow.Button1.click() 19 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad1.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # "도움말 > 메모장 정보" 메뉴를 선택합니다. 7 | app.UntitledNotepad.menu_select("Help->About Notepad") 8 | 9 | # "확인" 버튼을 눌러서 다이얼로그를 닫습니다. 10 | app.AboutNotepad.OK.click() 11 | 12 | # 메모장에 내용을 적습니다. 13 | app.UntitledNotepad.Edit.type_keys("pywinauto Works!", with_spaces = True) 14 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad2.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # "도움말 > 메모장 정보" 메뉴를 선택합니다. 7 | app.UntitledNotepad.menu_select("도움말(&H)->About Notepad") 8 | 9 | # "확인" 버튼을 눌러서 다이얼로그를 닫습니다. 10 | app.AboutNotepad.OK.click() 11 | 12 | # 메모장에 내용을 적습니다. 13 | app.UntitledNotepad.Edit.type_keys("pywinauto Works!", with_spaces = True) 14 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad3.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # "도움말 > 메모장 정보" 메뉴를 선택합니다. 7 | app.UntitledNotepad.menu_select("도움말(&H)->메모장 정보(&A)") 8 | 9 | # "확인" 버튼을 눌러서 다이얼로그를 닫습니다. 10 | app.AboutNotepad.OK.click() 11 | 12 | # 메모장에 내용을 적습니다. 13 | app.UntitledNotepad.Edit.type_keys("pywinauto Works!", with_spaces = True) 14 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad4.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # "도움말 > 메모장 정보" 메뉴를 선택합니다. 7 | app.UntitledNotepad.menu_select("도움말(&H)->메모장 정보(&A)") 8 | 9 | # "확인" 버튼을 눌러서 다이얼로그를 닫습니다. 10 | app.메모장_정보.확인.click() 11 | 12 | # 메모장에 내용을 적습니다. 13 | app.UntitledNotepad.Edit.type_keys("pywinauto Works!", with_spaces = True) 14 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad5.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # 메모장에 code를 적습니다. 7 | app.UntitledNotepad.Edit.type_keys("print {(}'test'{)}", with_spaces = True) 8 | 9 | # "파일 > 저장" 메뉴를 실행합니다. 10 | app.UntitledNotepad.menu_select("파일(&F)->저장(&S)") 11 | 12 | # "다른 이름으로 저장" 창의 속성을 리스트업 합니다. 13 | app.다른_이름으로_저장.print_control_identifiers() 14 | -------------------------------------------------------------------------------- /예제 소스 코드/13교시/notepad_final.py: -------------------------------------------------------------------------------- 1 | from pywinauto.application import Application 2 | 3 | # 메모장를 띄웁니다. 4 | app = Application().start("notepad.exe") 5 | 6 | # 메모장에 code를 적습니다. 7 | app.UntitledNotepad.Edit.type_keys("print {(}'test'{)}", with_spaces = True) 8 | 9 | # "파일' > 저장" 메뉴를 실행 합니다. 10 | app.UntitledNotepad.menu_select("파일(&F)->저장(&S)") 11 | 12 | # '다른 이름으로 저장' 창의 속성을 리스트업 합니다. 13 | # app.다른_이름으로_저장.print_control_identifiers() 14 | 15 | # 파일 전체 경로를 입력 합니다. 16 | app.다른_이름으로_저장.Edit1.SetEditText("c:\python\code\samplecode.py") 17 | 18 | # "파일이름" 콤보박스에서 파일 종류를 선택 합니다. 19 | app.다른_이름으로_저장.ComboBox2.Select("모든 파일") 20 | 21 | # "파일형식" 콤보박스에서 인코딩을 선택 합니다. 22 | app.다른_이름으로_저장.ComboBox3.Select("UTF-8") 23 | 24 | # 바로 저장 버튼을 누르면 미처 콤보 박스가 안 바꿔져 에러가 나서 1초 시간을 주었습니다 25 | import time 26 | time.sleep(1.0) 27 | 28 | # 저장 버튼을 누릅니다. 29 | app.다른_이름으로_저장.Button1.click() -------------------------------------------------------------------------------- /예제 소스 코드/14교시/14교시 샘플.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/14교시/14교시 샘플.zip -------------------------------------------------------------------------------- /예제 소스 코드/14교시/ftpupload_final.py: -------------------------------------------------------------------------------- 1 | import ftplib 2 | import os 3 | from datetime import datetime 4 | import subprocess 5 | from subprocess import check_output 6 | 7 | ### 압축 코드 8 | # 서브 프로세스를 실행시켜 7z 명령어로 압축을 합니다. 9 | check_output('c:\\\"Program Files\"\\7-Zip\\7z a -r -tzip c:\\python\\code\\zipfile\\backup_\"%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%\".zip c:\\python\\code\source\\*.txt c:\\python\\code\\source\\*.jpg', shell=True) 10 | print ("zip done") 11 | 12 | ### ftp 코드 13 | # datatime 모듈을 사용하여 오늘의 압축 파일 이름을 생성합니다. 14 | filename = "backup_" + datetime.now().strftime("%Y%m%d") + ".zip" 15 | 16 | # ftp 에 연결합니다. 17 | ftp = ftplib.FTP("127.0.0.1") 18 | ftp.login("ftpuser", "test1234") 19 | 20 | # ftp 루트에서 mybackup 폴더로 이동합니다. 21 | ftp.cwd("/mybackup") 22 | 23 | # zip 파일이 있는 폴더로 이동 합니다. 24 | os.chdir(r"c:\python\code\zipfile") 25 | 26 | # 바이너리 형태로 파일을 업로드 합니다. 27 | ftp.storbinary("STOR " + filename, open(filename, 'rb')) 28 | print ("ftp upload done") 29 | 30 | ### 삭제 코드 31 | # 7일 이상 된 백업 폴더의 backup zip 파일을 삭제 합니다. 32 | subprocess.call('forfiles /p "c:\\python\\code\\zipfile " /s /m backup*.zip /d -7 /c "cmd /c del @path"', shell=True) 33 | print ("del done") 34 | -------------------------------------------------------------------------------- /예제 소스 코드/14교시/ftpuploadtest.py: -------------------------------------------------------------------------------- 1 | import ftplib 2 | import os 3 | from datetime import datetime 4 | 5 | # datatime 모듈을 사용하여 오늘의 압축 파일 이름을 생성합니다. 6 | filename = "backup_" + datetime.now().strftime("%Y%m%d") + ".zip" 7 | 8 | # ftp에 연결합니다. 9 | ftp = ftplib.FTP("127.0.0.1") 10 | ftp.login("ftpuser", "test1234") 11 | 12 | # ftp 에서 myback 폴더로 이동합니다. 13 | ftp.cwd("/mybackup") 14 | 15 | # zip 파일이 있는 폴더로 이동합니다. 16 | os.chdir(r"c:\python\code\zipfile") 17 | 18 | # 바이너리 형태로 파일을 업로드 합니다. 19 | ftp.storbinary("STOR " + filename, open(filename, 'rb')) 20 | 21 | print ('upload completed') 22 | -------------------------------------------------------------------------------- /예제 소스 코드/14교시/ziptest.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | from subprocess import check_output 3 | 4 | # 서브 프로세스를 실행 시킵니다. 5 | check_output('c:\"Program Files"\7-Zip\7z a -r -tzip c:\python\code\zipfile\backup_"%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%".zip c:\python\code\source\*.txt c:\python\code\source\*.jpg', shell=True) 6 | 7 | print ("zip done") -------------------------------------------------------------------------------- /예제 소스 코드/14교시/ziptest2.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | from subprocess import check_output 3 | 4 | # 서브 프로세스를 실행 시킵니다. 5 | check_output('c:\\\"Program Files\"\\7-Zip\\7z a -r -tzip c:\\python\\code\\zipfile\\backup_\"%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%\".zip c:\\python\\code\source\\*.txt c:\\python\\code\\source\\*.jpg', shell=True) 6 | 7 | print ("zip done") -------------------------------------------------------------------------------- /예제 소스 코드/14교시/미니문법/datetime_sample.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | # 오늘의 날짜 및 시간을 얻어옵니다. 4 | today = datetime.today() 5 | # 오늘이 몇 번째 요일인지 알아옵니다(0~6:월~일) 6 | weekday = today.weekday() 7 | 8 | # 오늘의 날짜를 출력 합니다. 9 | print("today: " + str(today)) 10 | 11 | # 오늘이 월요일인지 체크해 출력합니다. 12 | if weekday == 0: 13 | print("today is monday") 14 | else: 15 | print("today is not monday") -------------------------------------------------------------------------------- /예제 소스 코드/14교시/미니문법/ftpupload_final_use_run.py: -------------------------------------------------------------------------------- 1 | import ftplib 2 | import os 3 | from datetime import datetime 4 | from subprocess import run 5 | 6 | ### 압축 코드 7 | # 서브 프로세스를 실행시켜 7z 명령어로 압축을 합니다. 8 | run('c:\\\"Program Files\"\\7-Zip\\7z a -r -tzip c:\\python\\code\\zipfile\\backup_\"%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%\".zip c:\\python\\code\source\\*.txt c:\\python\\code\\source\\*.jpg', shell=True) 9 | print ("zip done") 10 | 11 | ### ftp 코드 12 | # datatime 모듈을 사용하여 오늘의 압축 파일 이름을 생성합니다. 13 | filename = "backup_" + datetime.now().strftime("%Y%m%d") + ".zip" 14 | 15 | # ftp 에 연결합니다. 16 | ftp = ftplib.FTP("127.0.0.1") 17 | ftp.login("ftpuser", "test1234") 18 | 19 | # ftp 루트에서 mybackup 폴더로 이동합니다. 20 | ftp.cwd("/mybackup") 21 | 22 | # zip 파일이 있는 폴더로 이동 합니다. 23 | os.chdir(r"c:\python\code\zipfile") 24 | 25 | # 바이너리 형태로 파일을 업로드 합니다. 26 | ftp.storbinary("STOR " + filename, open(filename, 'rb')) 27 | print ("ftp upload done") 28 | 29 | # 7일 이상 된 백업 폴더의 backup zip 파일을 삭제 합니다. 30 | run('forfiles /p "c:\\python\\code\\zipfile " /s /m backup*.zip /d -7 /c "cmd /c del @path"', shell=True) 31 | print ("del done") 32 | -------------------------------------------------------------------------------- /예제 소스 코드/14교시/미니문법/os_sample.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # 현재 디렉토리를 얻어와 출력 합니다. 4 | print("current directory is: " + os.getcwd()) -------------------------------------------------------------------------------- /예제 소스 코드/15교시/numpy_test.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | # 2*2 크기인 array "a" 를 만듭니다. 4 | a = np.array([[1, 2], [3, 4]]) 5 | 6 | # a array 원소들에 모두 1을 더해 array "b" 를 만듭니다 7 | b = a + 1 8 | print (b) 9 | 10 | # b array 를 재 정렬해 1*4 로 array "c" 를 만듭니다. 11 | c = np.reshape(b, (1,4)) 12 | print (c) 13 | 14 | # c array 원소들에 log 함수를 적용해 array "d" 를 만듭니다. 15 | d = np.log(c) 16 | print (d) 17 | -------------------------------------------------------------------------------- /예제 소스 코드/15교시/pandas_test.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | 4 | # pandas 용 dataframe 을 만듭니다(메모리 버전 엑셀이라고 생각합니다) 5 | df = pd.DataFrame({'A': 'fruit drink cookie fruit'.split(), 6 | 'B': 'orange Coke chocopie mango'.split(), 7 | 'C': np.arange(4)}) 8 | 9 | # 만든 dataframe 을 출력합니다. 10 | print(df) 11 | print('------------------------------') 12 | 13 | # 뿌리면 아래와 같이 생겼습니다. 14 | # A B C 15 | # 0 fruit orange 0 16 | # 1 drink juice 1 17 | # 2 cookie chocopie 2 18 | # 3 fruit mango 3 19 | 20 | # df 중에 A 열이 fruit 인 데이터만 추출 하여 출력 합니다. 21 | print(df.loc[df['A'] == 'fruit']) 22 | -------------------------------------------------------------------------------- /예제 소스 코드/15교시/scipy_test.py: -------------------------------------------------------------------------------- 1 | from scipy.integrate import quad 2 | 3 | 4 | # y=x^2 함수를 정의 합니다. 5 | def myfn(x): 6 | return x**2 7 | 8 | 9 | # x 는 0~1 사이의 구간에 대해서 해당 함수를 적분 합니다. 10 | ans, err = quad(myfn, 0, 1) 11 | print (ans) -------------------------------------------------------------------------------- /예제 소스 코드/15교시/sympy_test.py: -------------------------------------------------------------------------------- 1 | from sympy import * 2 | 3 | # x 를 심볼로 지정합니다. 4 | x = symbols('x') 5 | 6 | # y = x^2 - x - 6 의 인수분해를 합니다. 7 | ans = factor(x**2 - x - 6) 8 | print(ans) 9 | -------------------------------------------------------------------------------- /예제 소스 코드/16교시/matplotlib_test.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | # 점을 찍을 좌표 대한 리스트를 생성합니다. 5 | x = [1, 2, -3, -4] 6 | y = [1, -2, 3, -4] 7 | 8 | # 각각의 색이 담긴 리스트를 돌리면서, 각각의 점에 대해서 색을 지정합니다. 9 | for i, color in enumerate(['red', 'black', 'blue', 'brown'], start=0): 10 | plt.plot(x[i], y[i], 'ro', color=color) 11 | 12 | # 그래프의 제목을 넣습니다. 13 | plt.title('Simple Graph') 14 | 15 | # 그리드를 보이게 합니다. 16 | plt.grid(True) 17 | 18 | # 가로세로 1:1 비율을 만듭니다. 19 | plt.axes().set_aspect('equal', 'datalim') 20 | 21 | # x,y 축 이름을 넣습니다. 22 | plt.ylabel('X Axis') 23 | plt.xlabel('Y Axis') 24 | 25 | # 그래프가 보이는 최대 최소 범위를 지정 합니다. 26 | plt.xlim((-8,8)) 27 | plt.ylim((-8,8)) 28 | 29 | # x, y 축을 보이게 합니다. 30 | plt.axhline(y=0, color='k') 31 | plt.axvline(x=0, color='k') 32 | 33 | # 그린 그래프를 화면에 출력 합니다. 34 | plt.show() -------------------------------------------------------------------------------- /예제 소스 코드/16교시/plotly_offline.py: -------------------------------------------------------------------------------- 1 | import plotly.graph_objs as go 2 | import numpy as np 3 | import plotly.offline as offline 4 | 5 | # 랜덤 값을 만듭니다. 6 | N = 1000 7 | random_x = np.random.randn(N) 8 | random_y = np.random.randn(N) 9 | 10 | # 트레이스를 만듭니다. 11 | trace = go.Scatter( 12 | x = random_x, 13 | y = random_y, 14 | mode = 'markers' 15 | ) 16 | 17 | data = [trace] 18 | 19 | # 그래프를 그립니다. 20 | offline.plot(data, filename='basic-scatter.html') -------------------------------------------------------------------------------- /예제 소스 코드/16교시/plotly_online.py: -------------------------------------------------------------------------------- 1 | import plotly 2 | import plotly.plotly as py 3 | import plotly.graph_objs as go 4 | import numpy as np 5 | 6 | # API 키 정보를 넣습니다. 7 | plotly.tools.set_credentials_file(username='사용자 이름', api_key='사용자의 API KEY') 8 | 9 | # 랜덤 값을 만듭니다. 10 | N = 1000 11 | random_x = np.random.randn(N) 12 | random_y = np.random.randn(N) 13 | 14 | # 트레이스를 만듭니다. 15 | trace = go.Scatter( 16 | x = random_x, 17 | y = random_y, 18 | mode = 'markers' 19 | ) 20 | 21 | data = [trace] 22 | 23 | # 그래프를 그립니다. 24 | py.plot(data, filename='basic-scatter') -------------------------------------------------------------------------------- /예제 소스 코드/17교시/least_numpy_sample.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # x, y 좌표 지정(y = 3x + 1), 방정식 모델을 지정합니다. 5 | x = np.array([1, 2, 5, 7]) 6 | y = np.array([4, 7, 16, 22]) 7 | A = np.vstack([x, np.ones(len(x))]).T 8 | 9 | # 선형대수 라이브러리의 least squre 호출합니다. 10 | slope, intercept = np.linalg.lstsq(A, y)[0] 11 | print("기울기:", slope, ", 절편:", intercept) 12 | 13 | # 기존 값을 점으로, 찾은 기울기를 선으로 그립니다.. 14 | plt.plot(x, y, 'o', label='Original data', markersize=10) 15 | plt.plot(x, slope*x + intercept, 'r', label='Fitted line') 16 | plt.legend() 17 | plt.show() 18 | -------------------------------------------------------------------------------- /예제 소스 코드/17교시/least_scipy_sample.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from scipy import stats 4 | 5 | # NumPy 배열에 데이터를 지정합니다. 6 | x = np.array([1, 2, 5, 7]) 7 | y = np.array([4, 7, 16, 22]) 8 | 9 | # 데이터에 맞는 값을 찾습니다(Slope: 기울기, Intercept: 절편). 10 | slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) 11 | print ("기울기와 절편", slope, intercept) 12 | print ("R-squared", r_value**2) 13 | 14 | # 데이터를 점으로, 찾은 선과 같이 화면에 표시합니다. 15 | plt.plot(x, y, 'o', label='original data') 16 | plt.plot(x, intercept + slope*x, 'r', label='fitted line') 17 | plt.legend() 18 | plt.show() 19 | -------------------------------------------------------------------------------- /예제 소스 코드/17교시/least_tensorflow_sample.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy 3 | import matplotlib.pyplot as plt 4 | rng = numpy.random 5 | 6 | # 파라매터들 변수를 조정 합니다. 7 | # 변화 수치, 전체 실행 수, 몇 번마다 화면에 로그를 보여 줄지를 정합니다. 8 | learning_rate = 0.01 9 | training_epochs = 1000 10 | display_step = 50 11 | 12 | # 훈련용 데이터를 지정합니다. 13 | train_X = numpy.asarray([1, 2, 5, 7]) 14 | train_Y = numpy.asarray([4, 7, 16, 22]) 15 | n_samples = train_X.shape[0] 16 | 17 | # 텐서플로우 변수들을 만듭니다. 18 | X = tf.placeholder("float") 19 | Y = tf.placeholder("float") 20 | 21 | W = tf.Variable(rng.randn(), name="weight") 22 | b = tf.Variable(rng.randn(), name="bias") 23 | 24 | # 모델 'y = Wx + b' 를 정의합니다. 25 | pred = tf.add(tf.multiply(X, W), b) 26 | 27 | # least square 공식을 이용하여 최소값을 만들 요소를 지정합니다. 28 | cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples) 29 | 30 | # 기울기를 보정하는 경사하강법이란것을 사용하고, 비용을 최소화 하는 방향으로 학습 합니다. 31 | optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 32 | 33 | # 초기화를 합니다. 34 | init = tf.global_variables_initializer() 35 | 36 | # 텐서플로우를 기동 합니다. 37 | with tf.Session() as sess: 38 | sess.run(init) 39 | 40 | # 데이터를 넣습니다. 41 | for epoch in range(training_epochs): 42 | for (x, y) in zip(train_X, train_Y): 43 | sess.run(optimizer, feed_dict={X: x, Y: y}) 44 | 45 | # 50번 마다 로그 뿌려서 찾는 값 변화를 보여 줍니다. 46 | if (epoch+1) % display_step == 0: 47 | c = sess.run(cost, feed_dict={X: train_X, Y:train_Y}) 48 | print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \ 49 | "W=", sess.run(W), "b=", sess.run(b)) 50 | 51 | # 완료가 되면 결과를 출력합니다. 52 | print("Optimization Finished!") 53 | training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y}) 54 | print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n') 55 | 56 | # 찾은 결과를 그래프로 보여줍니다. 57 | plt.plot(train_X, train_Y, 'ro', label='Original data') 58 | plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') 59 | plt.legend() 60 | plt.show() 61 | -------------------------------------------------------------------------------- /예제 소스 코드/17교시/opencv_fft_sample.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from matplotlib import pyplot as plt 4 | 5 | # 이미지를 읽어옵니다. 6 | img = cv2.imread('testpic.jpg',0) 7 | 8 | # 푸리에 변환을 하고 중심 점을 맞춥니다. 9 | f = np.fft.fft2(img) 10 | fshift = np.fft.fftshift(f) 11 | magnitude_spectrum = 20*np.log(np.abs(fshift)) 12 | 13 | # 작은 마스크를 만들어서 푸리에 변환한 영역의 가운데를 지워 버립니다.(하이패스 필터) 14 | rows, cols = img.shape 15 | crow,ccol = rows//2 , cols//2 16 | fshift[crow-30:crow+30, ccol-30:ccol+30] = 0 17 | f_ishift = np.fft.ifftshift(fshift) 18 | 19 | # 다시 이미지로 역변환 합니다. 20 | img_back = np.fft.ifft2(f_ishift) 21 | img_back = np.abs(img_back) 22 | 23 | # 그림으로 보여줍니다. 24 | plt.subplot(131),plt.imshow(img, cmap = 'gray') 25 | plt.title('Input Image'), plt.xticks([]), plt.yticks([]) 26 | plt.subplot(132),plt.imshow(magnitude_spectrum, cmap = 'gray') 27 | plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([]) 28 | plt.subplot(133),plt.imshow(img_back, cmap = 'gray') 29 | plt.title('Image after HPF'), plt.xticks([]), plt.yticks([]) 30 | 31 | plt.show() 32 | 33 | print ("ok") 34 | -------------------------------------------------------------------------------- /예제 소스 코드/18교시/ASP/ajax_sample.asp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/ASP/ajax_sample.asp -------------------------------------------------------------------------------- /예제 소스 코드/18교시/ASP/ajax_sub.asp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/ASP/ajax_sub.asp -------------------------------------------------------------------------------- /예제 소스 코드/18교시/ASP/supermarket_sample.asp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/ASP/supermarket_sample.asp -------------------------------------------------------------------------------- /예제 소스 코드/18교시/ASP/test.asp: -------------------------------------------------------------------------------- 1 | <% 2 | Response.Write "Hello ASP" 3 | %> 4 | -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/css_sample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/css_sample.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/font_sample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/font_sample.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/form_sample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/form_sample.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/table_sample1.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/table_sample1.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/table_sample2.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/table_sample2.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/HTML/table_sample3.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/HTML/table_sample3.html -------------------------------------------------------------------------------- /예제 소스 코드/18교시/JavaScript/colorchange_sample.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | 16 | 17 | 18 | 19 |

Color Change

20 | First name: 21 |
22 | Last name: 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /예제 소스 코드/18교시/JavaScript/menu_sample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/18교시/JavaScript/menu_sample.html -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/myweb.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template 3 | import pyodbc 4 | 5 | server = 'localhost' 6 | database = 'mytest' 7 | username = 'pyuser' 8 | password = 'test1234' 9 | cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) 10 | cursor = cnxn.cursor() 11 | 12 | # flask 웹서버를 실행 합니다. 13 | app = Flask(__name__) 14 | 15 | # "sqltable" 이라는 URL 인자를 "showsql" 이라는 함수로 연결합니다. 16 | @app.route("/sqltable") 17 | def showsql(): 18 | # SQL 문을 실행하여 supermarket 테이블에서 데이터를 가져옵니다. 19 | cursor.execute('SELECT Itemno, Category, FoodName, Company, Price FROM supermarket(nolock);') 20 | # 가져온 모든 데이터를 mytable.html 파일과 함께 랜더링 하여 표현합니다. 21 | return render_template('myweb.html', rows = cursor.fetchall()) 22 | 23 | # 이 웹서버는 127.0.0.1 주소를 가지면 포트 5000번에 동작하며, 에러를 자세히 표시합니다 24 | if __name__ == "__main__": 25 | app.run(host='127.0.0.1',port=5000,debug=True) 26 | -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/myweb_d3.py: -------------------------------------------------------------------------------- 1 | import json 2 | import flask 3 | import numpy as np 4 | 5 | app = flask.Flask(__name__) 6 | 7 | # d3sample 을 호출했을때의 템플릿을 설정합니다. 8 | @app.route("/d3sample") 9 | def showsample(): 10 | return flask.render_template("d3sample.html") 11 | 12 | # D3에서 가져갈 data url을 호출하면 반환할 json 데이터 만들어 냅니다. 13 | @app.route("/data") 14 | def data(): 15 | # 그래프를 그릴 데이터를 지정 합니다. 16 | x = ['2017-07-10', '2017-07-11', '2017-07-12', '2017-07-13', '2017-07-14'] 17 | y = [58.13, 53.98, 67.00, 89.70, 99.00] 18 | 19 | # 리스트를 json 데이터로 변환 합니다. 20 | return json.dumps([{"date": x[i], "close": y[i]} 21 | for i in range(5)]) 22 | 23 | # 앞과 비슷한데 문법만 조금 틀립니다. 24 | if __name__ == "__main__": 25 | port = 5000 26 | app.debug = True 27 | app.run(port=port) 28 | -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/myweb_mat.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | from flask import Flask, render_template, send_file, make_response 3 | import flask 4 | from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | 8 | app = flask.Flask(__name__) 9 | 10 | # mypic 을 호출하면 mypic.html 로 렌더링 합니다. 11 | @app.route('/mypic') 12 | def mypic(): 13 | return flask.render_template("mypic.html") 14 | 15 | # matplotlib 그래프 파일을 생성하여 MIME 형식으로 보내줍니다. 16 | @app.route('/plot') 17 | def plot(): 18 | 19 | # 그림판을 준비합니다. 20 | fig, axis = plt.subplots(1) 21 | 22 | # 데이터를 준비합니다. 23 | y = [1,2,3,4,5] 24 | x = [0,2,1,3,4] 25 | 26 | # 데이터를 캔버스에 그립니다. 27 | axis.plot(x,y) 28 | canvas = FigureCanvas(fig) 29 | 30 | # 그려진 img 파일 내용을 html 랜더링 쪽에 전송합니다. 31 | img = BytesIO() 32 | fig.savefig(img) 33 | img.seek(0) 34 | return send_file(img, mimetype='image/png') 35 | 36 | 37 | if __name__ == '__main__': 38 | port = 5000 39 | app.debug = True 40 | app.run(port=port) 41 | -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/templates/d3sample.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 19 | 20 | 21 | 22 | 23 | 90 | -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/templates/mypic.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | image 4 | 5 | 6 | matplotlib 으로부터 만들어진 이미지 7 |

8 | Image Placeholder 9 | 10 | 11 | -------------------------------------------------------------------------------- /예제 소스 코드/19교시/flaskweb/templates/myweb.html: -------------------------------------------------------------------------------- 1 |  2 | {% for row in rows %} 3 | 4 | {% for data in row %} 5 | 6 | {% endfor %} 7 | 8 | {% endfor %} 9 |
{{ data }}
10 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/db.sqlite3 -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/djangoweb/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/djangoweb/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangoweb project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.0.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '31i(xl(-ud^+(7c5vdvre3iljf6x)pih75)+ku_vq1zgv=604m' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'supermarket', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'djangoweb.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'djangoweb.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'sql_server.pyodbc', 80 | 'NAME': 'mytest', 81 | 'USER': 'pyuser', 82 | 'PASSWORD': 'test1234', 83 | 'HOST': 'localhost', 84 | 'PORT': '1433', 85 | 86 | 'OPTIONS': { 87 | 'driver': 'ODBC Driver 13 for SQL Server', 88 | }, 89 | }, 90 | } 91 | 92 | 93 | 94 | 95 | # Password validation 96 | # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators 97 | 98 | AUTH_PASSWORD_VALIDATORS = [ 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 107 | }, 108 | { 109 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 110 | }, 111 | ] 112 | 113 | 114 | # Internationalization 115 | # https://docs.djangoproject.com/en/2.0/topics/i18n/ 116 | 117 | LANGUAGE_CODE = 'en-us' 118 | 119 | TIME_ZONE = 'UTC' 120 | 121 | USE_I18N = True 122 | 123 | USE_L10N = True 124 | 125 | USE_TZ = True 126 | 127 | 128 | # Static files (CSS, JavaScript, Images) 129 | # https://docs.djangoproject.com/en/2.0/howto/static-files/ 130 | 131 | STATIC_URL = '/static/' 132 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/urls.py: -------------------------------------------------------------------------------- 1 | """djangoweb URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.urls import include, path 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('', include('supermarket.urls')), 23 | ] 24 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/djangoweb/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangoweb project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoweb.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoweb.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SupermarketConfig(AppConfig): 5 | name = 'supermarket' 6 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/migrations/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb/supermarket/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/models.py: -------------------------------------------------------------------------------- 1 | # This is an auto-generated Django model module. 2 | # You'll have to do the following manually to clean this up: 3 | # * Rearrange models' order 4 | # * Make sure each model has one field with primary_key=True 5 | # * Make sure each ForeignKey has `on_delete` set to the desired behavior. 6 | # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table 7 | # Feel free to rename the models, but don't rename db_table values or field names. 8 | from django.db import models 9 | 10 | 11 | class Play(models.Model): 12 | original = models.CharField(max_length=30, blank=True, null=True) 13 | encrypted = models.CharField(max_length=200, blank=True, null=True) 14 | decrypted = models.CharField(max_length=30, blank=True, null=True) 15 | 16 | class Meta: 17 | managed = False 18 | db_table = 'play' 19 | 20 | 21 | class Supermarket(models.Model): 22 | itemno = models.IntegerField(db_column='Itemno', blank=True, null=True) # Field name made lowercase. 23 | category = models.CharField(db_column='Category', max_length=20, blank=True, null=True) # Field name made lowercase. 24 | foodname = models.CharField(db_column='FoodName', max_length=30, blank=True, null=True) # Field name made lowercase. 25 | company = models.CharField(db_column='Company', max_length=20, blank=True, null=True) # Field name made lowercase. 26 | price = models.IntegerField(db_column='Price', blank=True, null=True) # Field name made lowercase. 27 | 28 | class Meta: 29 | managed = False 30 | db_table = 'supermarket' 31 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/templates/d3sample.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 114 | 115 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/templates/index.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 장고샘플 6 | 7 | 8 |

동작함

9 | 10 | 11 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/templates/super.html: -------------------------------------------------------------------------------- 1 |  2 | {% for super in supers %} 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | {% endfor %} 11 |
{{ super.itemno }}{{ super.category }}{{ super.foodname }}{{ super.company }}{{ super.price }}
12 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/urls.py: -------------------------------------------------------------------------------- 1 | """djangoweb20 URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from supermarket import views 19 | 20 | urlpatterns = [ 21 | path('', views.HomePageView.as_view()), 22 | path('supermk', views.supermk), 23 | path('data', views.data, name='data'), 24 | path('d3sample', views.d3sample), 25 | ] 26 | 27 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb/supermarket/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views.generic import TemplateView 3 | 4 | # Create views 5 | class HomePageView(TemplateView): 6 | def get(self, request, **kwargs): 7 | return render(request, 'index.html', context=None) 8 | 9 | from .models import Supermarket 10 | 11 | def supermk(request): 12 | supers = Supermarket.objects.all() 13 | return render(request, 'super.html', {'supers': supers}) 14 | 15 | import json 16 | import numpy as np 17 | from django.http import JsonResponse 18 | def data(request): 19 | x = ['2017-07-10', '2017-07-11', '2017-07-12', '2017-07-13', '2017-07-14'] 20 | y = [58.13, 53.98, 67.00, 89.70, 99.00] 21 | 22 | myData = json.dumps([{"date": x[i], "close": y[i]} for i in range(5)]) 23 | return JsonResponse(myData, safe=False) 24 | 25 | 26 | def d3sample(request): 27 | return render(request, 'd3sample.html', context=None) -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/db.sqlite3 -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for djangoweb project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.0.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '31i(xl(-ud^+(7c5vdvre3iljf6x)pih75)+ku_vq1zgv=604m' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'supermarket', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'djangoweb.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'djangoweb.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'sql_server.pyodbc', 80 | 'NAME': 'mytest', 81 | 'USER': 'pyuser', 82 | 'PASSWORD': 'test1234', 83 | 'HOST': 'localhost', 84 | 'PORT': '1433', 85 | 86 | 'OPTIONS': { 87 | 'driver': 'ODBC Driver 13 for SQL Server', 88 | }, 89 | }, 90 | } 91 | 92 | 93 | 94 | 95 | # Password validation 96 | # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators 97 | 98 | AUTH_PASSWORD_VALIDATORS = [ 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 107 | }, 108 | { 109 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 110 | }, 111 | ] 112 | 113 | 114 | # Internationalization 115 | # https://docs.djangoproject.com/en/2.0/topics/i18n/ 116 | 117 | LANGUAGE_CODE = 'en-us' 118 | 119 | TIME_ZONE = 'UTC' 120 | 121 | USE_I18N = True 122 | 123 | USE_L10N = True 124 | 125 | USE_TZ = True 126 | 127 | 128 | # Static files (CSS, JavaScript, Images) 129 | # https://docs.djangoproject.com/en/2.0/howto/static-files/ 130 | 131 | STATIC_URL = '/static/' 132 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/urls.py: -------------------------------------------------------------------------------- 1 | """djangoweb URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.urls import include, path 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('', include('supermarket.urls')), 23 | ] 24 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/djangoweb/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for djangoweb project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoweb.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoweb.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SupermarketConfig(AppConfig): 5 | name = 'supermarket' 6 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/migrations/__init__.py -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/20교시/djangoweb_json_modify/supermarket/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/models.py: -------------------------------------------------------------------------------- 1 | # This is an auto-generated Django model module. 2 | # You'll have to do the following manually to clean this up: 3 | # * Rearrange models' order 4 | # * Make sure each model has one field with primary_key=True 5 | # * Make sure each ForeignKey has `on_delete` set to the desired behavior. 6 | # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table 7 | # Feel free to rename the models, but don't rename db_table values or field names. 8 | from django.db import models 9 | 10 | 11 | class Play(models.Model): 12 | original = models.CharField(max_length=30, blank=True, null=True) 13 | encrypted = models.CharField(max_length=200, blank=True, null=True) 14 | decrypted = models.CharField(max_length=30, blank=True, null=True) 15 | 16 | class Meta: 17 | managed = False 18 | db_table = 'play' 19 | 20 | 21 | class Supermarket(models.Model): 22 | itemno = models.IntegerField(db_column='Itemno', blank=True, null=True) # Field name made lowercase. 23 | category = models.CharField(db_column='Category', max_length=20, blank=True, null=True) # Field name made lowercase. 24 | foodname = models.CharField(db_column='FoodName', max_length=30, blank=True, null=True) # Field name made lowercase. 25 | company = models.CharField(db_column='Company', max_length=20, blank=True, null=True) # Field name made lowercase. 26 | price = models.IntegerField(db_column='Price', blank=True, null=True) # Field name made lowercase. 27 | 28 | class Meta: 29 | managed = False 30 | db_table = 'supermarket' 31 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/templates/d3sample.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 114 | 115 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/templates/index.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 장고샘플 6 | 7 | 8 |

동작함

9 | 10 | 11 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/templates/super.html: -------------------------------------------------------------------------------- 1 |  2 | {% for super in supers %} 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | {% endfor %} 11 |
{{ super.itemno }}{{ super.category }}{{ super.foodname }}{{ super.company }}{{ super.price }}
12 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/urls.py: -------------------------------------------------------------------------------- 1 | """djangoweb20 URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from supermarket import views 19 | 20 | urlpatterns = [ 21 | path('', views.HomePageView.as_view()), 22 | path('supermk', views.supermk), 23 | path('data', views.data, name='data'), 24 | path('d3sample', views.d3sample), 25 | ] 26 | 27 | -------------------------------------------------------------------------------- /예제 소스 코드/20교시/djangoweb_json_modify/supermarket/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views.generic import TemplateView 3 | 4 | # Create views 5 | class HomePageView(TemplateView): 6 | def get(self, request, **kwargs): 7 | return render(request, 'index.html', context=None) 8 | 9 | from .models import Supermarket 10 | 11 | def supermk(request): 12 | supers = Supermarket.objects.all() 13 | return render(request, 'super.html', {'supers': supers}) 14 | 15 | import json 16 | import numpy as np 17 | from django.http import JsonResponse 18 | def data(request): 19 | x = np.array(['2017-07-10', '2017-07-11', '2017-07-12', '2017-07-13', '2017-07-14']) 20 | y = np.array([58.13, 53.98, 67.00, 89.70, 99.00]) 21 | 22 | mylist = [] 23 | 24 | for intnum in range(5): 25 | mylist.append({"date" : x[intnum], "close" : y[intnum]}) 26 | 27 | return JsonResponse(mylist, safe=False) 28 | 29 | def d3sample(request): 30 | return render(request, 'd3sample.html', context=None) -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_01.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE [dbo].[supermarket]( 2 | [Itemno] [int] NULL, 3 | [Category] [char](20) NULL, 4 | [FoodName] [char](30) NULL, 5 | [Company] [char](20) NULL, 6 | [Price] [int] NULL 7 | ) 8 | -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_02.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_02.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_03.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_03.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_04.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_04.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_05.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_05.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_06.txt: -------------------------------------------------------------------------------- 1 | select * from supermarket; -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_07.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_07.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_08.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_08.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_09.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE [dbo].[play]( 2 | [original] [char](30) NULL, 3 | [encrypted] [char](200) NULL, 4 | [decrypted] [char](30) NULL, 5 | ) 6 | -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_10.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_10.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_11.txt: -------------------------------------------------------------------------------- 1 | select * from play(nolock) -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_12.txt: -------------------------------------------------------------------------------- 1 | update play set encrypted ='', decrypted = '' 2 | where original = 'secret' 3 | -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_13.txt: -------------------------------------------------------------------------------- 1 | SELECT COLUMN_NAME 2 | FROM INFORMATION_SCHEMA.COLUMNS 3 | WHERE TABLE_NAME = 'supermarket' 4 | 5 | -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_14.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/예제 소스 코드/query 모음/query_14.txt -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_15.txt: -------------------------------------------------------------------------------- 1 | c:\"Program Files"\7-Zip\7z a -r -tzip c:\python\code\zipfile\backup_"%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%".zip c:\python\code\source\*.txt c:\python\code\source\*.jpg -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_16.txt: -------------------------------------------------------------------------------- 1 | use mytest 2 | go 3 | ALTER TABLE dbo.supermarket 4 | ADD id INT IDENTITY 5 | 6 | ALTER TABLE dbo.supermarket 7 | ADD CONSTRAINT PK_supermarket 8 | PRIMARY KEY(id) 9 | 10 | select * from dbo.supermarket(nolock) 11 | -------------------------------------------------------------------------------- /예제 소스 코드/query 모음/query_17.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE [dbo].[supermarket]( 2 | [Itemno] [int] NOT NULL PRIMARY KEY, 3 | [Category] [char](20) NULL, 4 | [FoodName] [char](30) NULL, 5 | [Company] [char](20) NULL, 6 | [Price] [int] NULL 7 | ) 8 | -------------------------------------------------------------------------------- /책속 링크 모음.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjpublic/python_study/5962145ada503ffebc0fda8ecd779b624c947b02/책속 링크 모음.txt --------------------------------------------------------------------------------