6/05/2020

Python - Iterators and Iterables : What Are They and How Do They Work?

**  Iterators and Iterables : What Are They and How Do They Work?


==========================================

nums = [1, 2, 3]

for num in nums:
print(num)

---------------------------------

1
2
3

==========================================
==========================================

nums = [1, 2, 3]

print(dir(nums))

---------------------------------

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', 

'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 

'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', 

'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 

'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 

'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 

'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 

'reverse', 'sort']

==========================================
==========================================

nums = [1, 2, 3]

print(next(nums))

---------------------------------

  File "C:\Users\purunet\Documents\py9\ii.py", line 7, in <module>
    print(next(nums))
TypeError: 'list' object is not an iterator


==========================================
==========================================

nums = [1, 2, 3]

i_nums = nums.__iter__()


print(i_nums)
print(dir(i_nums))

---------------------------------

<list_iterator object at 0x02461D18>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 

'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', 

'__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', 

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', 

'__sizeof__', '__str__', '__subclasshook__']

==========================================
==========================================

nums = [1, 2, 3]

i_nums = iter(nums)


print(i_nums)
print(dir(i_nums))

---------------------------------

<list_iterator object at 0x00E51D18>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 

'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', 

'__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', 

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', 

'__sizeof__', '__str__', '__subclasshook__']

==========================================
==========================================

nums = [1, 2, 3]

i_nums = iter(nums)


print(next(i_nums))

---------------------------------

1

==========================================
==========================================

nums = [1, 2, 3]

i_nums = iter(nums)


print(next(i_nums))
print(next(i_nums))
print(next(i_nums))

---------------------------------

1
2
3

==========================================
==========================================

nums = [1, 2, 3]

i_nums = iter(nums)


print(next(i_nums))
print(next(i_nums))
print(next(i_nums))
print(next(i_nums))

---------------------------------

1Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py9\ii.py", line 10, in <module>

2
3
    print(next(i_nums))
StopIteration

==========================================
==========================================

nums = [1, 2, 3]

i_nums = iter(nums)


while True:
try:
item = next(i_nums)
print(item)
except StopIteration:
break

---------------------------------

1
2
3

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

nums = MyRange(1, 10)

for num in nums:
print(num)

---------------------------------

1
2
3
4
5
6
7
8
9

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

nums = MyRange(1, 10)

print(next(nums))

---------------------------------

1

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

nums = MyRange(1, 10)

print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))

---------------------------------

1
2
3
4

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

def my_range(start, end):
current = start
while current < end:
yield current
current += 1


nums = my_range(1, 10)

print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))

---------------------------------

1
2
3
4

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

def my_range(start, end):
current = start
while current < end:
yield current
current += 1


nums = my_range(1, 10)

for num in nums:
print(num)

---------------------------------

1
2
3
4
5
6
7
8
9

==========================================
==========================================

class MyRange:

def __init__(self, start, end):
self.value = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current

def my_range(start):
current = start
while True:
yield current
current += 1


nums = my_range(1)

for num in nums:
print(num)

---------------------------------

1에서부터 시작해서, 정지명령을 내릴 때 까지 계속 1씩 증가.

==========================================

Python - 참고

** 참고


==========================================


C:\Users\purunet\Documents\Flask_Blog>pip install flask-wtf
Collecting flask-wtf
  Downloading Flask_WTF-0.14.3-py2.py3-none-any.whl (13 kB)
Collecting WTForms
  Downloading WTForms-2.3.1-py2.py3-none-any.whl (169 kB)
     |████████████████████████████████| 169 kB 327 kB/s
Requirement already satisfied: itsdangerous in c:\users\purunet\appdata\local\pr
ograms\python\python38-32\lib\site-packages (from flask-wtf) (1.1.0)
Requirement already satisfied: Flask in c:\users\purunet\appdata\local\programs\
python\python38-32\lib\site-packages (from flask-wtf) (1.1.2)
Requirement already satisfied: MarkupSafe in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from WTForms->flask-wtf) (1.1.1)
Requirement already satisfied: Jinja2>=2.10.1 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-wtf) (2.11.2)
Requirement already satisfied: click>=5.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from Flask->flask-wtf) (7.1.2)
Requirement already satisfied: Werkzeug>=0.15 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-wtf) (1.0.1)
Installing collected packages: WTForms, flask-wtf
Successfully installed WTForms-2.3.1 flask-wtf-0.14.3


==========================================

C:\Users\purunet\Documents\Flask_Blog>pip install email_validator
Collecting email_validator
  Downloading email_validator-1.1.1-py2.py3-none-any.whl (17 kB)
Requirement already satisfied: idna>=2.0.0 in c:\users\purunet\appdata\local\pro
grams\python\python38-32\lib\site-packages (from email_validator) (2.9)
Collecting dnspython>=1.15.0
  Downloading dnspython-1.16.0-py2.py3-none-any.whl (188 kB)
     |████████████████████████████████| 188 kB 327 kB/s
Installing collected packages: dnspython, email-validator
Successfully installed dnspython-1.16.0 email-validator-1.1.1


==========================================

C:\Users\purunet\Documents\Flask_Blog>pip install flask_sqlalchemy
Collecting flask_sqlalchemy
  Downloading Flask_SQLAlchemy-2.4.1-py2.py3-none-any.whl (17 kB)
Collecting SQLAlchemy>=0.8.0
  Downloading SQLAlchemy-1.3.17-cp38-cp38-win32.whl (1.2 MB)
     |████████████████████████████████| 1.2 MB 364 kB/s
Requirement already satisfied: Flask>=0.10 in c:\users\purunet\appdata\local\pro
grams\python\python38-32\lib\site-packages (from flask_sqlalchemy) (1.1.2)
Requirement already satisfied: Werkzeug>=0.15 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask>=0.10->flask_sqlalchem
y) (1.0.1)
Requirement already satisfied: itsdangerous>=0.24 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from Flask>=0.10->flask_sqlal
chemy) (1.1.0)
Requirement already satisfied: click>=5.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from Flask>=0.10->flask_sqlalchemy) (
7.1.2)
Requirement already satisfied: Jinja2>=2.10.1 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask>=0.10->flask_sqlalchem
y) (2.11.2)
Requirement already satisfied: MarkupSafe>=0.23 in c:\users\purunet\appdata\loca
l\programs\python\python38-32\lib\site-packages (from Jinja2>=2.10.1->Flask>=0.1
0->flask_sqlalchemy) (1.1.1)
Installing collected packages: SQLAlchemy, flask-sqlalchemy
Successfully installed SQLAlchemy-1.3.17 flask-sqlalchemy-2.4.1


==========================================

C:\Users\purunet\Documents\Flask_Blog>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from flaskblog import db
C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\lib\site-packages\fla
sk_sqlalchemy\__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICAT
IONS adds significant overhead and will be disabled by default in the future.  S
et it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(

>>> db.create_all()
>>> from flaskblog import User, Post
>>> user_1 = User(username='LinuxerHAN', email='LinuxerHAN@gmail.com', password=
'password')
>>> db.session.add(user_1)
>>> user_2 = User(username='SeokDu', email='seokdu@demo.com', password='password
')
>>> db.session.add(user_2)
>>> db.session.commit()
>>> User.query.all()
[User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg'), User('SeokDu', 'seok
du@demo.com', 'default.jpg')]
>>> User.query.first()
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')
>>> User.query.filter_by(username='LinuxerHAN').all()
[User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')]
>>> User.query.filter_by(username='LinuxerHAN').first()
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')
>>> user = User.query.filter_by(username='LinuxerHAN').first()
>>> user
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')
>>> user.id
1
>>> user = User.query.get(1)
>>> user
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')
>>> user.posts
[]
>>> user.id
1
>>> post_1 = Post(title='Blog 1', content='First Post Content!', user_id=user.id
)
>>> post_2 = Post(title='Blog 2', content='Second Post Content!', user_id=user.i
d)
>>> db.session.add(post_1)
>>> db.session.add(post_2)
>>> db.session.commit()
>>> user.posts
[Post('Blog 1', '2020-05-24 13:22:56.712866'), Post('Blog 2', '2020-05-24 13:22:
56.713867')]
>>> for post in user.posts:
...     print(post.title)
...
Blog 1
Blog 2

>>> post = Post.query.first()
>>>
>>> post
Post('Blog 1', '2020-05-24 13:22:56.712866')
>>> post.user_id
1
>>> post.author
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')

>>> db.drop_all()
>>> db.create_all()
>>> User.query.all()
[]
>>> Post.query.all()
[]

==========================================

C:\Users\purunet\Documents\LinuxerHAN>tree/f
폴더 PATH의 목록입니다.
볼륨 일련 번호가 B273F7ED 840E:6930입니다.
C:.
│  run.py
│
└─flaskblog
    │  forms.py
    │  models.py
    │  routes.py
    │  site.db
    │  __init__.py
    │
    ├─snippets
    │      article.html
    │      main.html
    │      navigation.html
    │
    ├─static
    │      main.css
    │
    ├─templates
    │      about.html
    │      home.html
    │      layout.html
    │      login.html
    │      register.html
    │
    └─__pycache__
            forms.cpython-38.pyc
            models.cpython-38.pyc
            routes.cpython-38.pyc
            __init__.cpython-38.pyc

==========================================

C:\Users\purunet>pip install flask-bcrypt
Collecting flask-bcrypt
  Downloading Flask-Bcrypt-0.7.1.tar.gz (5.1 kB)
Requirement already satisfied: Flask in c:\users\purunet\appdata\local\programs\
python\python38-32\lib\site-packages (from flask-bcrypt) (1.1.2)
Collecting bcrypt
  Downloading bcrypt-3.1.7-cp38-cp38-win32.whl (26 kB)
Requirement already satisfied: Jinja2>=2.10.1 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-bcrypt) (2.11.2
)
Requirement already satisfied: click>=5.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from Flask->flask-bcrypt) (7.1.2)
Requirement already satisfied: itsdangerous>=0.24 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from Flask->flask-bcrypt) (1.
1.0)
Requirement already satisfied: Werkzeug>=0.15 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-bcrypt) (1.0.1)

Collecting cffi>=1.1
  Downloading cffi-1.14.0-cp38-cp38-win32.whl (165 kB)
     |████████████████████████████████| 165 kB 363 kB/s
Requirement already satisfied: six>=1.4.1 in c:\users\purunet\appdata\roaming\py
thon\python38\site-packages (from bcrypt->flask-bcrypt) (1.14.0)
Requirement already satisfied: MarkupSafe>=0.23 in c:\users\purunet\appdata\loca
l\programs\python\python38-32\lib\site-packages (from Jinja2>=2.10.1->Flask->fla
sk-bcrypt) (1.1.1)
Collecting pycparser
  Downloading pycparser-2.20-py2.py3-none-any.whl (112 kB)
     |████████████████████████████████| 112 kB 2.2 MB/s
Building wheels for collected packages: flask-bcrypt
  Building wheel for flask-bcrypt (setup.py) ... done
  Created wheel for flask-bcrypt: filename=Flask_Bcrypt-0.7.1-py3-none-any.whl s
ize=5017 sha256=ca1e80cdcec68bef7a093c1a06048973aa8866a5cf060e97cd27e9b8cd191001

  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\8a\d9\0e\
dc762c4ebc76f581397a2e25991db6efd148640b5616ab9210
Successfully built flask-bcrypt
Installing collected packages: pycparser, cffi, bcrypt, flask-bcrypt
Successfully installed bcrypt-3.1.7 cffi-1.14.0 flask-bcrypt-0.7.1 pycparser-2.2
0


==========================================

C:\Users\purunet>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask_bcrypt import Bcrypt
>>> bcrypt = Bcrypt()
>>> bcrypt.generate_password_hash('testing')
b'$2b$12$mFAQ6BDudqfCpZPhMckeROvqlnaEsM5NgfwSeASq8bphdpZcCcpc.'
>>> bcrypt.generate_password_hash('testing').decode('utf-8')
'$2b$12$avJZl7.zrIANX69rakHJTO/rJ8602zoq7VXQVEb3lV8HOPFoaCCba'
>>> bcrypt.generate_password_hash('testing').decode('utf-8')
'$2b$12$pht9HoEEBCpPZdHz35wNpeGuc.27zH2lfJc.bzctjGJs2bqpoITf2'
>>> bcrypt.generate_password_hash('testing').decode('utf-8')
'$2b$12$B2euNgvatxQUY04ewJ5Jt.uk5SixLUoy28nEWnlWxNC67tTWmaVvS'

==========================================

>>> hashed_pw = bcrypt.generate_password_hash('testing').decode('utf-8')
>>> bcrypt.check_password_hash(hashed_pw, 'password')
False
>>> bcrypt.check_password_hash(hashed_pw, 'testing')
True

==========================================


C:\Users\purunet\Documents\LinuxerHAN>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from flaskblog import db
C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\lib\site-packages\fla
sk_sqlalchemy\__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICAT
IONS adds significant overhead and will be disabled by default in the future.  S
et it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
>>> from flaskblog.models import User
>>> user = User.query.first()
>>> user
User('LinuxerHAN', 'LinuxerHAN@gmail.com', 'default.jpg')
>>> user.password
'$2b$12$V2KdD62Q6WJ7JBry4xTQveOjgEZjIjtlrj7KKfiwhVhh2nR5RR8CW'
>>>

==========================================


C:\Users\purunet\Documents\LinuxerHAN>pip install flask-login
Collecting flask-login
  Downloading Flask_Login-0.5.0-py2.py3-none-any.whl (16 kB)
Requirement already satisfied: Flask in c:\users\purunet\appdata\local\programs\
python\python38-32\lib\site-packages (from flask-login) (1.1.2)
Requirement already satisfied: Werkzeug>=0.15 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-login) (1.0.1)
Requirement already satisfied: click>=5.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from Flask->flask-login) (7.1.2)
Requirement already satisfied: itsdangerous>=0.24 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from Flask->flask-login) (1.1
.0)
Requirement already satisfied: Jinja2>=2.10.1 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-login) (2.11.2)

Requirement already satisfied: MarkupSafe>=0.23 in c:\users\purunet\appdata\loca
l\programs\python\python38-32\lib\site-packages (from Jinja2>=2.10.1->Flask->fla
sk-login) (1.1.1)
Installing collected packages: flask-login
Successfully installed flask-login-0.5.0

==========================================

C:\Users\purunet\Documents\LinuxerHAN>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from flaskblog.models import Post
C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\lib\site-packages\fla
sk_sqlalchemy\__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICAT
IONS adds significant overhead and will be disabled by default in the future.  S
et it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
>>> posts = Post.query.all()
>>> for post in posts:
...     print(post)
...
Post('My first Post', '2020-05-25 12:42:07.786133')
Post('A Second Post', '2020-05-25 14:07:08.138319')

>>>

==========================================

C:\Users\purunet\Documents\LinuxerHAN>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> s = Serializer('secret', 30)
>>> token = s.dumps({'user_id': 1}).decode('utf-8')
>>> token
'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU5MDQ2MDI1NCwiZXhwIjoxNTkwNDYwMjg0fQ.eyJ1c2VyX2lk
IjoxfQ.jtMEIcCLnCQ42jUPm-AUXl0VR_jds6cdQotZ5Aifk67GuiZmaLnrQtWrpnM6QiqZUxLFeJNjk
9od8VYMk8XCog'
>>> s.loads(token)
{'user_id': 1}
>>> s.loads(token)
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\lib\site-pack
ages\itsdangerous\jws.py", line 202, in loads
    raise SignatureExpired(
itsdangerous.exc.SignatureExpired: Signature expired
>>>

==========================================

C:\Users\purunet\Documents\LinuxerHAN>pip install flask-mail
Collecting flask-mail
  Downloading Flask-Mail-0.9.1.tar.gz (45 kB)
     |████████████████████████████████| 45 kB 68 kB/s
Requirement already satisfied: Flask in c:\users\purunet\appdata\local\programs\
python\python38-32\lib\site-packages (from flask-mail) (1.1.2)
Collecting blinker
  Downloading blinker-1.4.tar.gz (111 kB)
     |████████████████████████████████| 111 kB 547 kB/s
Requirement already satisfied: Jinja2>=2.10.1 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-mail) (2.11.2)
Requirement already satisfied: Werkzeug>=0.15 in c:\users\purunet\appdata\local\
programs\python\python38-32\lib\site-packages (from Flask->flask-mail) (1.0.1)
Requirement already satisfied: itsdangerous>=0.24 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from Flask->flask-mail) (1.1.
0)
Requirement already satisfied: click>=5.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from Flask->flask-mail) (7.1.2)
Requirement already satisfied: MarkupSafe>=0.23 in c:\users\purunet\appdata\loca
l\programs\python\python38-32\lib\site-packages (from Jinja2>=2.10.1->Flask->fla
sk-mail) (1.1.1)
Building wheels for collected packages: flask-mail, blinker
  Building wheel for flask-mail (setup.py) ... done
  Created wheel for flask-mail: filename=Flask_Mail-0.9.1-py3-none-any.whl size=
7573 sha256=1c196c8f11ccb7fab4fb811cebc030397e8c4e28f068f8d8f19785b0f2bfa156
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\98\bc\8c\
34c329e4d7efeaf7b9886db0c76d0b23170e54de443f688e3c
  Building wheel for blinker (setup.py) ... done
  Created wheel for blinker: filename=blinker-1.4-py3-none-any.whl size=13455 sh
a256=42f9c6ac0dcfe0462b0d67224988cbf450eeb3c70539a14b0182a2697f174104
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\b7\a5\68\
fe632054a5eadd531c7a49d740c50eb6adfbeca822b4eab8d4
Successfully built flask-mail blinker
Installing collected packages: blinker, flask-mail
Successfully installed blinker-1.4 flask-mail-0.9.1

==========================================

C:\Users\purunet\Documents\LinuxerHAN>pip install django
Requirement already satisfied: django in c:\users\purunet\appdata\local\programs
\python\python38-32\lib\site-packages (3.0.6)
Requirement already satisfied: asgiref~=3.2 in c:\users\purunet\appdata\local\pr
ograms\python\python38-32\lib\site-packages (from django) (3.2.7)
Requirement already satisfied: pytz in c:\users\purunet\appdata\local\programs\p
ython\python38-32\lib\site-packages (from django) (2020.1)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\purunet\appdata\local
\programs\python\python38-32\lib\site-packages (from django) (0.3.1)

C:\Users\purunet\Documents\LinuxerHAN>python -m django --version
3.0.6

==========================================

C:\Users\purunet\Documents\LinuxerHAN>django-admin

Type 'django-admin help ' for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not properly conf
igured (error: Requested setting INSTALLED_APPS, but settings are not configured
. You must either define the environment variable DJANGO_SETTINGS_MODULE or call
 settings.configure() before accessing settings.).


==========================================

C:\Users\purunet\Documents\LinuxerHAN>django-admin startproject django_project

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you
 apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 28, 2020 - 16:35:27
Django version 3.0.6, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py startapp blog

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>tree/f
폴더 PATH의 목록입니다.
볼륨 일련 번호가 7995090C 840E:6930입니다.
C:.
│  db.sqlite3
│  manage.py
│
├─blog
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
└─django_project
    │  asgi.py
    │  settings.py
    │  urls.py
    │  wsgi.py
    │  __init__.py
    │
    └─__pycache__
            settings.cpython-38.pyc
            urls.cpython-38.pyc
            wsgi.cpython-38.pyc
            __init__.cpython-38.pyc

==========================================

https://getbootstrap.com/docs/4.0/getting-started/introduction/#starter-template

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py makemigrat
ions
No changes detected

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py createsupe
ruser
Username (leave blank to use 'specialist'): LinuxerHAN
Email address: linuxerhan@gmail.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py makemigrat
ions
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model Post

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py sqlmigrate
 blog 0001
BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "titl
e" varchar(100) NOT NULL, "content" text NOT NULL, "date_posted" datetime NOT NU
LL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIA
LLY DEFERRED);
CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id");
COMMIT;

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying blog.0001_initial... OK


==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py shell
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Post
>>> from django.contrib.auth.models import User
>>> User.objects.all()
, ]>
>>> User.objects.first()

>>> User.objects.filter(username='LinuxerHAN')
]>
>>> User.objects.filter(username='LinuxerHAN').first()

>>> user = User.objects.filter(username='LinuxerHAN').first()
>>> user

>>> user.id
1
>>> user.pk
1
>>> user = User.objects.get(id=1)
>>> user

>>> Post.objects.all()

>>> post_1 = Post(title='Blog 1', content='First Post Content!', author=user)
>>> Post.objects.all()

>>> post_1.save()
>>> Post.objects.all()
]>

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py shell
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Post
>>> from django.contrib.auth.models import User
>>> Post.objects.all()
]>
>>> user = User.objects.filter(username='LinuxerHAN').first()
>>> user

>>> post_2 = Post(title='Blog 2', content='Second Post Content!', author_id=user
.id)
>>> post_2.save()
>>> Post.objects.all()
, ]>
>>> post = Post.objects.first()
>>> post.content
'First Post Content!'
>>> post.date_posted
datetime.datetime(2020, 6, 1, 10, 4, 19, 148035, tzinfo=)
>>> post.author

>>> post.author.email
'linuxerhan@gmail.com'
>>> user

>>> user.post_set
.RelatedManager object at 0x02B2D910>
>>> user.post_set.all()
, ]>
>>> user.post_set
.RelatedManager object at 0x02B2D910>
>>> user.post_set.all()
, ]>
>>> user.post_set.create(title='Blog 3', content='Third Post Content!')

>>> Post.objects.all()
, , ]>

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project> pip install django-crispy-
forms
Requirement already satisfied: django-crispy-forms in c:\users\purunet\appdata\l
ocal\programs\python\python38-32\lib\site-packages (1.9.1)

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py makemigrat
ions
No changes detected

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions, users
Running migrations:
  Applying users.0001_initial... OK

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py shell
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> user = User.objects.filter(username='LinuxerHAN').first()
>>> user

>>> user.profile

>>> user.profile.image

>>> user.profile.image.width
802
>>> user.profile.image.url
'profile_pics/default2.jpg'
>>> user = User.objects.filter(username='SeokDu').first()
>>> user

>>> user.profile.image


==========================================

>>> import json
>>> from blog.models import Post
>>> with open('posts.json') as f:
...     posts_json = json.load(f)
...
>>> for post in posts_json:
...     post = Post(title=post['title'], content=post['content'], author_id=post
['user_id'])
...     post.save()
...

==========================================

C:\Users\purunet\Documents\LinuxerHAN\django_project>python manage.py shell
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.paginator import Paginator
>>> posts = ['1', '2', '3', '4', '5']
>>> p = Paginator(posts, 2)
>>> p.num_pages
3
>>> for page in p.page_range:
...     print(page)
...
1
2
3
>>> p1 = p.page(1)
>>> p1

>>> p1.number
1
>>> p1.object_list
['1', '2']
>>> p1.has_previous()
False
>>> p1.has_next()
True
>>> p1.next_page_number()
2
>>> exit()


==========================================


5/27/2020

Python - Set Methods and Operations to Solve Common Problems

** Set Methods and Operations to Solve Common Problems


==========================================

s1 = set([1, 2, 3, 4, 5])

print(s1)

---------------------------------

{1, 2, 3, 4, 5}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}

print(s1)

---------------------------------

{1, 2, 3, 4, 5}

---------------------------------

==========================================

s1 = set()

print(s1)

---------------------------------

set()

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5, 1, 2, 3}

print(s1)

---------------------------------

{1, 2, 3, 4, 5}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s1.add(6)
print(s1)

---------------------------------

{1, 2, 3, 4, 5, 6}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s1.update([6, 7, 8])
print(s1)

---------------------------------

{1, 2, 3, 4, 5, 6, 7, 8}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s2 = {7, 8, 9}
s1.update([6, 7, 8], s2)
print(s1)

---------------------------------

{1, 2, 3, 4, 5, 6, 7, 8, 9}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s1.remove(5)
print(s1)

---------------------------------

{1, 2, 3, 4}

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s1.remove(6)
print(s1)

---------------------------------

    s1.remove(6)
KeyError: 6

---------------------------------

==========================================

s1 = {1, 2, 3, 4, 5}
s1.discard(6)
print(s1)

---------------------------------

{1, 2, 3, 4, 5}

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s1.intersection(s2)

print(s4)

---------------------------------

{2, 3}


---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s1.intersection(s2, s3)

print(s4)

---------------------------------

{3}

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s1.difference(s2)

print(s4)

---------------------------------

{1}

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s2.difference(s1)

print(s4)

---------------------------------

{4}

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s2.difference(s1, s3)

print(s4)

---------------------------------

set()

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s3.difference(s1, s2)

print(s4)

---------------------------------

{5}

---------------------------------

==========================================


s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s1.symmetric_difference(s2)

print(s4)

---------------------------------

{1, 4}

---------------------------------

==========================================

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

s4 = s2.symmetric_difference(s1)

print(s4)

---------------------------------

{1, 4}

---------------------------------

==========================================

l1 = [1, 2, 3, 1, 2, 3]

l2 = list(set(l1))

print(l2)

---------------------------------

[1, 2, 3]

---------------------------------

==========================================

employees = ['Corey', 'Jim', 'Steven', 'April', 'Judy', 'Jenn', 'John', 'Jane']

gym_members = ['April', 'John', 'Corey']

developers = ['Judy', 'Corey', 'Steven', 'Jane', 'April']

result = set(gym_members).intersection(developers)

print(result)

---------------------------------

{'Corey', 'April'}

---------------------------------

==========================================

employees = ['Corey', 'Jim', 'Steven', 'April', 'Judy', 'Jenn', 'John', 'Jane']

gym_members = ['April', 'John', 'Corey']

developers = ['Judy', 'Corey', 'Steven', 'Jane', 'April']

result = set(employees).difference(gym_members, developers)

print(result)


---------------------------------

{'Jenn', 'Jim'}

---------------------------------

==========================================

employees = ['Corey', 'Jim', 'Steven', 'April', 'Judy', 'Jenn', 'John', 'Jane']

gym_members = ['April', 'John', 'Corey']

developers = ['Judy', 'Corey', 'Steven', 'Jane', 'April']

if 'Corey' in developers:
    print('Found!')

# O(n) for list
# O(1) for a set

---------------------------------

Found!

---------------------------------


5/23/2020

Python - Full-Featured Web App Part 1 - Getting Started

** Full-Featured Web App Part 1 - Getting Started


==========================================

C:\Users\purunet>pip install flask
Collecting flask
  Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
     |████████████████████████████████| 94 kB 154 kB/s
Collecting Jinja2>=2.10.1
  Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB)
     |████████████████████████████████| 125 kB 656 kB/s
Collecting Werkzeug>=0.15
  Downloading Werkzeug-1.0.1-py2.py3-none-any.whl (298 kB)
     |████████████████████████████████| 298 kB 2.2 MB/s
Collecting itsdangerous>=0.24
  Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB)
Collecting click>=5.1
  Downloading click-7.1.2-py2.py3-none-any.whl (82 kB)
     |████████████████████████████████| 82 kB 188 kB/s
Collecting MarkupSafe>=0.23
  Downloading MarkupSafe-1.1.1-cp38-cp38-win32.whl (16 kB)
Installing collected packages: MarkupSafe, Jinja2, Werkzeug, itsdangerous, click
, flask
Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2
 flask-1.1.2 itsdangerous-1.1.0

==========================================

C:\Users\purunet>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask
>>> exit()

==========================================

C:\Users\purunet\Documents\Flask_Blog>set FLASK_APP = flaskblog.py

==========================================

C:\Users\purunet\Documents\Flask_Blog>python flaskblog.py
 * Serving Flask app "flaskblog" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployme
nt.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 234-451-768
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 12:48:56] " [37mGET / HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 12:48:56] " [33mGET /favicon.ico HTTP/1.1 [0m" 404 -
 * Detected change in 'C:\\Users\\purunet\\Documents\\Flask_Blog\\flaskblog.py',
 reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 234-451-768
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 12:49:33] " [37mGET / HTTP/1.1 [0m" 200 -

==========================================

from flask import Flask

app = Flask(__name__)



@app.route('/')

def hello_world():

return 'Hello World!'



if __name__ == '__main__':

app.run()

---------------------------------





---------------------------------

==========================================

C:\Users\purunet\Documents\Flask_Blog>set FLASK_DEBUG=1

C:\Users\purunet\Documents\Flask_Blog>flask run
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployme
nt.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 556-684-567
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/May/2020 14:14:14] " [35m [1mGET / HTTP/1.1 [0m" 500 -
Traceback (most recent call last):
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 314, in _load_app
    self._load_unlocked()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\Lib\site-pack
ages\flask\cli.py", line 398, in load_app
    raise NoAppException(
flask.cli.NoAppException: Could not locate a Flask application. You did not prov
ide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was
 not found in the current directory.
127.0.0.1 - - [23/May/2020 14:14:14] " [37mGET /?__debugger__=yes&cmd=resource&f
=style.css HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:14] " [37mGET /?__debugger__=yes&cmd=resource&f
=debugger.js HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:16] " [37mGET /?__debugger__=yes&cmd=resource&f
=jquery.js HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:17] " [37mGET /?__debugger__=yes&cmd=resource&f
=console.png HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:18] " [37mGET /?__debugger__=yes&cmd=resource&f
=ubuntu.ttf HTTP/1.1 [0m" 200 -
127.0.0.1 - - [23/May/2020 14:14:18] " [37mGET /?__debugger__=yes&cmd=resource&f
=console.png HTTP/1.1 [0m" 200 -

---------------------------------





---------------------------------

==========================================

from flask import Flask
app = Flask(__name__)


@app.route("/")
def hello():
return "

Hello World!

"


if __name__ == '__main__':
app.run(debug=True)

---------------------------------





---------------------------------

==========================================

from flask import Flask
app = Flask(__name__)


@app.route("/")
@app.route("/home")
def home():
    return "

Home Page

"


@app.route("/about")
def about():
    return "

About Page

"


if __name__ == '__main__':
    app.run(debug=True)

---------------------------------








5/22/2020

Python - Ex Machina Easter Egg - Hidden Message within the Code

** Ex Machina Easter Egg - Hidden Message within the Code


==========================================


# BlueBook code decryption

import sys
def sieve(n):
    x = [1] * n
    x[1] = 0
    for i in range(2,n/2):
            j = 2 * i
            while j < n:
                    x[j]=0
                    j = j+i
    return x

def prime(n,x):
    i = 1
    j = 1
    while j <= n:
            if x[i] == 1:
                    j = j + 1
            i = i + 1
    return i - 1
x=sieve(10000)
code = [1206,301,384,5]
key =[1,1,2,2,]

sys.stdout.write("".join(chr(i) for i in [73,83,66,78,32,61,32]))
for i in range (0,4):
    sys.stdout.write(str(prime(code[i],x)-key[i]))

print

---------------------------------


Traceback (most recent call last):
  File "C:\Users\purunet\Documents\py7\sub1.py", line 23, in
    x=sieve(10000)
  File "C:\Users\purunet\Documents\py7\sub1.py", line 8, in sieve
    for i in range(2,n/2):
TypeError: 'float' object cannot be interpreted as an integer

---------------------------------

<~~ 차후에 해결.

---------------------------------

Python - Image Manipulation with Pillow

** Image Manipulation with Pillow


==========================================

from PIL import Image

image1 = Image.open('girl1.jpg')
image1.show()

---------------------------------




---------------------------------

==========================================

from PIL import Image

image1 = Image.open('apple1.jpg')
image1.save('apple1.png')

---------------------------------





---------------------------------

==========================================

from PIL import Image
import os

for f in os.listdir('.'):
if f.endswith('.jpg'):
print(f)

---------------------------------

apple1.jpg
apple2.jpg
apple3.jpg
apple4.jpg

---------------------------------

==========================================

from PIL import Image
import os

for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)
i.save('pngs/{}.png'.format(fn))

---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

size_300 = (300, 300)

for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)

i.thumbnail(size_300)
i.save('300/{}_300{}.png'.format(fn, fext))


---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

size_300 = (300, 300)
size_700 = (700, 700)


for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
fn, fext = os.path.splitext(f)

i.thumbnail(size_700)
i.save('700/{}_700{}.png'.format(fn, fext))

i.thumbnail(size_300)
i.save('300/{}_300{}.png'.format(fn, fext))


---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

image1 = Image.open('apple1.jpg')
image1.rotate(90).save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image
import os

image1 = Image.open('apple1.jpg')
image1.convert(mode='L').save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image, ImageFilter
import os

image1 = Image.open('apple1.jpg')
image1.filter(ImageFilter.GaussianBlur()).save('apple1_mod.jpg')

---------------------------------




---------------------------------

==========================================

from PIL import Image, ImageFilter
import os

image1 = Image.open('apple1.jpg')
image1.filter(ImageFilter.GaussianBlur(15)).save('apple1_mod.jpg')

---------------------------------




---------------------------------



Python - Else Clauses on Loops

** Else Clauses on Loops


==========================================

my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)

else:
print("Hit the For/Else Statement!")


---------------------------------

1
2
3
4
5
Hit the For/Else Statement!

---------------------------------

==========================================

num = 3

if num < 2 :
print("num is less than 2!")

else:
print("num is not less than 2!")

---------------------------------

num is not less than 2!

---------------------------------

==========================================


my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)
if i == 3:
break

else:
print("Hit the For/Else Statement!")

---------------------------------

1
2
3

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5]

for i in my_list:
print(i)
if i == 6:
break

else:
print("Hit the For/Else Statement!")


---------------------------------

1
2
3
4
5
Hit the For/Else Statement!

---------------------------------

==========================================

i = 1
while i <= 5:
    print(i)
    i += 1
    # if i == 3:
    #     break
else:
    print('Hit the While/Else Statement!')


---------------------------------

1
2
3
4
5
Hit the While/Else Statement!

---------------------------------

==========================================

i = 1
while i <= 5:
    print(i)
    i += 1
    if i == 3:
        break
else:
    print('Hit the While/Else Statement!')

---------------------------------

1
2

---------------------------------

==========================================

def find_index(to_search, target):
  for i, value in enumerate(to_search):
    if value == target:
      break
  else:
    return -1
  return i


my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'Steve')

print('Location of target is index: {}'.format(index_location))

---------------------------------

Location of target is index: -1

---------------------------------

==========================================

def find_index(to_search, target):
  for i, value in enumerate(to_search):
    if value == target:
      break
  else:
    return -1
  return i


my_list = ['HAN', 'Rick', 'John']
index_location = find_index(my_list, 'HAN')

print('Location of target is index: {}'.format(index_location))

---------------------------------

Location of target is index: 0

---------------------------------


Python - Preparing for a Python Interview: 10 Things You Should Know

** Preparing for a Python Interview: 10 Things You Should Know


==========================================

#1. Know how to write code on a whiteboard or paper.

#2. Know basic PYTHON control flow.

#3. Be able to discuss how you've used PYTHON.

#4. Know how to solve common interview problems.

#5. Know basic PYTHON data types and when to use them.

#6. Know how to use list comprehensions.

#7. Know how to use generators.

#8. Know the basics of OOP.

#9. Have PYTHON related questions ready to ask your interviewer.

#10. Know the basics of other technologies.

==========================================

==========================================

for i in range(1, 11):
print(i)

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

i = 1

while i <= 10:
print(i)
i += 1

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

a = 10
b = 20

if a < b:
print("{} is less than {}".format(a,b))

elif a == 20:
print("{} is equal to {}".format(a,b))

else:
print("{} is greater than {}".format(a,b))

---------------------------------

10 is less than 20

---------------------------------

==========================================

import os, glob

os.chdir("C:\\Users\\purunet\\Desktop\\LinuxerHaN blog")
for file in glob.glob("*.jpg"):
print(file)

---------------------------------

0.jpg
02.jpg
0b9414af9a817942fbf78c5f0d321b0d.jpg
1.jpg
1d080fc32a69dc4e278cbd8da186a043.jpg
2.jpg
2b553978cb8eadf4cf0813e67335bf97_11244249426.jpg
2bb176b1cf90c3dc3565bd48bc7e9ac4.jpg
3.jpg
4.jpg
4a23935e_2i.jpg
5.jpg
5ca203419e9574500442.jpg
6.jpg
6c1ee4b2992f99282927d6e2638eb490.jpg
7.jpg
8.jpg
8ab64f3ab4b6831f1843bd993b73d627.jpg

---------------------------------

==========================================

# fizz Buzz

for num in range(1, 101):
if num % 5 == 0 and num % 3 == 0:
print("FizzBuzz")
elif num %3 == 0:
print("Fizz")
elif num %5 == 0:
print("Buzz")
else:
print(num)

---------------------------------

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

---------------------------------

==========================================

python 3 에서는 range() 가 xrange() 를 대신함.

==========================================

==========================================

# Fibonacci Sequence

a, b = 0, 1

for i in range(0, 10):
print(a)
a, b = b, a + b

---------------------------------

0
1
1
2
3
5
8
13
21
34

---------------------------------

==========================================

# Lists

my_list = [10, 20, 30, 40, 50]

for i in my_list:
print(i)

---------------------------------

10
20
30
40
50

---------------------------------

==========================================

# Set

my_set = {10, 20, 30, 40, 50, 10, 20, 30, 40, 50}

for i in my_set:
print(i)

---------------------------------

40
10
50
20
30

---------------------------------

==========================================

# Tuples

my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

for i in my_tup:
print(i)

---------------------------------

1
2
3
4
5
6
7
8
9
10

---------------------------------

==========================================

# Dict

my_dict = {'name': 'Bronx', 'age': '2', 'occupation': "LinuxerHAN's Cat"}

for key, val in my_dict.items():
print("My {} is {}".format(key, val))

---------------------------------

My name is Bronx
My age is 2
My occupation is LinuxerHAN's Cat

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Give me each number in a list squared

squares = [num * num for num in my_list]

print(squares)

---------------------------------

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

---------------------------------

==========================================

# Fibonacci Generator

def fib(num):
a,b = 0,1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a+b

for item in fib(10):
print(item)


---------------------------------

1: 0
2: 1
3: 1
4: 2
5: 3
6: 5
7: 8
8: 13
9: 21
10: 34

---------------------------------

==========================================

class Person(object):
def __init__(self, name):
self.name = name

def reveal_identity(self):
print("My name is {}".format(self.name))


class SuperHero(Person):
def __init__(self, name, hero_name):
super(SuperHero, self).__init__(name)
self.hero_name = hero_name

def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print("...And I am {}".format(self.hero_name))


LinuxerHAN = Person('LinuxerHAN')
LinuxerHAN.reveal_identity()

---------------------------------

My name is LinuxerHAN

---------------------------------

==========================================


class Person(object):
def __init__(self, name):
self.name = name

def reveal_identity(self):
print("My name is {}".format(self.name))


class SuperHero(Person):
def __init__(self, name, hero_name):
super(SuperHero, self).__init__(name)
self.hero_name = hero_name

def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print("...And I am {}".format(self.hero_name))

SeokDu = SuperHero('SeokDu', 'Deadpool')
SeokDu.reveal_identity()

---------------------------------

My name is SeokDu
...And I am Deadpool

---------------------------------



5/21/2020

Python - Pipenv - Easily Manage Packages and Virtual Environments

** Pipenv - Easily Manage Packages and Virtual Environments


==========================================

C:\Users\purunet>pip install pipenv
Collecting pipenv
  Downloading pipenv-2018.11.26-py3-none-any.whl (5.2 MB)
     |████████████████████████████████| 5.2 MB 1.1 MB/s
Requirement already satisfied: certifi in c:\users\purunet\appdata\local\program
s\python\python38-32\lib\site-packages (from pipenv) (2020.4.5.1)
Requirement already satisfied: setuptools>=36.2.1 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from pipenv) (41.2.0)
Collecting virtualenv-clone>=0.2.5
  Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB)
Requirement already satisfied: pip>=9.0.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.1)
Collecting virtualenv
  Downloading virtualenv-20.0.21-py2.py3-none-any.whl (4.7 MB)
     |████████████████████████████████| 4.7 MB 4.4 kB/s
Collecting appdirs<2>=1.4.3
  Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting distlib<1>=0.3.0
  Downloading distlib-0.3.0.zip (571 kB)
     |████████████████████████████████| 571 kB 6.4 MB/s
Requirement already satisfied: six<2>=1.9.0 in c:\users\purunet\appdata\roaming
\python\python38\site-packages (from virtualenv->pipenv) (1.14.0)
Collecting filelock<4>=3.0.0
  Downloading filelock-3.0.12-py3-none-any.whl (7.6 kB)
Building wheels for collected packages: distlib
  Building wheel for distlib (setup.py) ... done
  Created wheel for distlib: filename=distlib-0.3.0-py3-none-any.whl size=340432
 sha256=fdea3c822aee056af092de0d42aca1b44c877bd62738907c3de567c5d03aaa94
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\eb\4e\d2\
a903d4184fb49e4ac06474d65715b129aee13d69f7d227e78e
Successfully built distlib
Installing collected packages: virtualenv-clone, appdirs, distlib, filelock, vir
tualenv, pipenv
Successfully installed appdirs-1.4.4 distlib-0.3.0 filelock-3.0.12 pipenv-2018.1
1.26 virtualenv-20.0.21 virtualenv-clone-0.5.4
WARNING: You are using pip version 20.1; however, version 20.1.1 is available.
You should consider upgrading via the 'c:\users\purunet\appdata\local\programs\p
ython\python38-32\python.exe -m pip install --upgrade pip' command.

C:\Users\purunet>python.exe -m pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
Successfully installed pip-20.1.1

C:\Users\purunet>pip install pipenv
Requirement already satisfied: pipenv in c:\users\purunet\appdata\local\programs
\python\python38-32\lib\site-packages (2018.11.26)
Requirement already satisfied: virtualenv in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.0.21)
Requirement already satisfied: pip>=9.0.1 in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from pipenv) (20.1.1)
Requirement already satisfied: virtualenv-clone>=0.2.5 in c:\users\purunet\appda
ta\local\programs\python\python38-32\lib\site-packages (from pipenv) (0.5.4)
Requirement already satisfied: setuptools>=36.2.1 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from pipenv) (41.2.0)
Requirement already satisfied: certifi in c:\users\purunet\appdata\local\program
s\python\python38-32\lib\site-packages (from pipenv) (2020.4.5.1)
Requirement already satisfied: distlib<1>=0.3.0 in c:\users\purunet\appdata\loc
al\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (0.3.
0)
Requirement already satisfied: appdirs<2>=1.4.3 in c:\users\purunet\appdata\loc
al\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (1.4.
4)
Requirement already satisfied: filelock<4>=3.0.0 in c:\users\purunet\appdata\lo
cal\programs\python\python38-32\lib\site-packages (from virtualenv->pipenv) (3.0
.12)
Requirement already satisfied: six<2>=1.9.0 in c:\users\purunet\appdata\roaming
\python\python38\site-packages (from virtualenv->pipenv) (1.14.0)

==========================================

C:\Users\purunet>pipenv install requests
Creating a virtualenv for this project…
Pipfile: C:\Users\purunet\Pipfile
Using c:\users\purunet\appdata\local\programs\python\python38-32\python.exe (3.8
.2) to create virtualenv…
[    ] Creating virtual environment...created virtual environment CPython3.8.2.f
inal.0-32 in 13262ms

  creator CPython3Windows(dest=C:\Users\purunet\.virtualenvs\purunet-gFaNxclQ, c
lear=False, global=False)

  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest
, via=copy, app_data_dir=C:\Users\purunet\AppData\Local\pypa\virtualenv\seed-app
-data\v1.0.1)

  activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,Pyth
onActivator,XonshActivator

Successfully created virtual environment!
Virtualenv location: C:\Users\purunet\.virtualenvs\purunet-gFaNxclQ
Creating a Pipfile for this project…
Installing requests…
Adding requests to Pipfile's [packages]…
Installation Succeeded
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Success!
Updated Pipfile.lock (fbd99e)!
Installing dependencies from Pipfile.lock (fbd99e)…
  ================================ 5/5 - 00:00:09
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

C:\Users\purunet>mkdir my_project

C:\Users\purunet>cd my_project

C:\Users\purunet\my_project>pipenv install requests
Installing requests…
Adding requests to Pipfile's [packages]…
Installation Succeeded
Installing dependencies from Pipfile.lock (fbd99e)…
  ================================ 5/5 - 00:00:03
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.


==========================================

C:\Users\purunet\my_project>pipenv shell
Launching subshell in virtual environment…
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

==========================================

(purunet-gFaNxclQ) C:\Users\purunet>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Users\\purunet\\.virtualenvs\\purunet-gFaNxclQ\\Scripts\\python.exe'
>>> import requests
>>> exit()

(purunet-gFaNxclQ) C:\Users\purunet>exit


==========================================

C:\Users\purunet\my_project>pipenv run python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Users\\purunet\\.virtualenvs\\purunet-gFaNxclQ\\Scripts\\python.exe'
>>> import requests
>>> exit()

==========================================

C:\Users\purunet\my_project>pipenv
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

Options:
  --where             Output project home information.
  --venv              Output virtualenv information.
  --py                Output Python interpreter information.
  --envs              Output Environment Variable options.
  --rm                Remove the virtualenv.
  --bare              Minimal output.
  --completion        Output completion (to be eval'd).
  --man               Display manpage.
  --support           Output diagnostic information for use in GitHub issues.
  --site-packages     Enable site-packages for the virtualenv.  [env var:
                      PIPENV_SITE_PACKAGES]
  --python TEXT       Specify which version of Python virtualenv should use.
  --three / --two     Use Python 3/2 when creating virtualenv.
  --clear             Clears caches (pipenv, pip, and pip-tools).  [env var:
                      PIPENV_CLEAR]
  -v, --verbose       Verbose mode.
  --pypi-mirror TEXT  Specify a PyPI mirror.
  --version           Show the version and exit.
  -h, --help          Show this message and exit.


Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check      Checks for security vulnerabilities and against PEP 508 markers
             provided in Pipfile.
  clean      Uninstalls all packages not specified in Pipfile.lock.
  graph      Displays currently-installed dependency graph information.
  install    Installs provided packages and adds them to Pipfile, or (if no
             packages are given), installs all packages from Pipfile.
  lock       Generates Pipfile.lock.
  open       View a given module in your editor.
  run        Spawns a command installed into the virtualenv.
  shell      Spawns a shell within the virtualenv.
  sync       Installs all packages specified in Pipfile.lock.
  uninstall  Un-installs a provided package and removes it from Pipfile.
  update     Runs lock, then sync.

==========================================

C:\Users\purunet\my_project>pip

Usage:
  pip [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependen
cies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring
                              environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be
                              used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be
                              used up to 3 times (corresponding to WARNING,
                              ERROR, and CRITICAL logging levels).
  --log                 Path to a verbose appending log.
  --proxy              Specify a proxy in the form
                              [user:passwd@]proxy.server:port.
  --retries          Maximum number of retries each connection should
                              attempt (default 5 times).
  --timeout              Set the socket timeout (default 15 seconds).
  --exists-action     Default action when a path already exists:
                              (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host    Mark this host or host:port pair as trusted,
                              even though it does not have valid or any HTTPS.
  --cert                Path to alternate CA bundle.
  --client-cert         Path to SSL client certificate, a single file
                              containing the private key and the certificate
                              in PEM format.
  --cache-dir

           Store the cache data in .
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine
                              whether a new version of pip is available for
                              download. Implied with --no-index.
  --no-color                  Suppress colored output
  --no-python-version-warning
                              Silence deprecation warnings for upcoming
                              unsupported Pythons.


==========================================

C:\Users\purunet\my_project>pipenv install pytest --dev
Installing pytest…
Adding pytest to Pipfile's [dev-packages]…
Installation Succeeded
Pipfile.lock (9e60ab) out of date, updating to (fbd99e)…
Locking [dev-packages] dependencies…
Success!
Locking [packages] dependencies…
Success!
Updated Pipfile.lock (9e60ab)!
Installing dependencies from Pipfile.lock (9e60ab)…
  ================================ 16/16 - 00:00:14
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

==========================================

C:\Users\purunet\my_project>pipenv graph
pytest==5.4.2
  - atomicwrites [required: >=1.0, installed: 1.4.0]
  - attrs [required: >=17.4.0, installed: 19.3.0]
  - colorama [required: Any, installed: 0.4.3]
  - more-itertools [required: >=4.0.0, installed: 8.3.0]
  - packaging [required: Any, installed: 20.4]
    - pyparsing [required: >=2.0.2, installed: 2.4.7]
    - six [required: Any, installed: 1.14.0]
  - pluggy [required: >=0.12,<1 .0="" 0.13.1="" installed:="" p="">  - py [required: >=1.5.0, installed: 1.8.1]
  - wcwidth [required: Any, installed: 0.1.9]
requests==2.23.0
  - certifi [required: >=2017.4.17, installed: 2020.4.5.1]
  - chardet [required: >=3.0.2,<4 3.0.4="" installed:="" p="">  - idna [required: >=2.5,<3 2.9="" installed:="" p="">  - urllib3 [required: >=1.21.1,<1 .26="" 1.25.9="" installed:="" p="">
==========================================