모각코/어쩌다보니 박준태가 또 조장이조

어쩌다보니 박준태가 또 조장이조 6차

potatoo 2024. 8. 12. 23:00
728x90

__name__ 변수와 "__main__"문자열

내장 변수 __name__는 스크립트를 실행하는 방법에 따라 문자열이 할당된다.

스크립트를 직접 실행하는 경우 __name__ 내장 변수를 "__main__"에 할당한다.

__name__ == "__main__"으로 작성하지만 동작은 __name__ = "__main__"으로 한다.

 

변수와 문자열이 같은지 확인하기 위해 if 블록을 사용할 수 있다.

if __name__ == "__main__":
	myfunc()

 

#one.py
def func():
	print("FUNC() IN ONE.PY")

print("TOP LEVEL IN ONE.PY")

if __name__ == '__main__':
	print('ONE.PY is being run directly!')
else:
	print('ONE.PY has been imported!')

one.py를 호출할 때마다 명령문을 출력하고, one.py가 main 스크립트라면, 즉 명령어에서 직접 one.py를 호출하고 있다면 ONE.PY is being run directly를 그렇지 않고, 변수 이름이 main으로 설정되지 않았다면 ONE.PY has been impored!를 출력한다.

#two.py
import one

print("TOP LEVEL IN TWO.PY")

one.func()

if __name__ == '__main__':
	print('TWO.PY is being run directly!')
else:
	print('TWO.PY has been imported!')

 

일반적으로 직접 실행 여부를 확인할 때 여기서 사용한 이 방식을 사용하지는 않는다.

대신 SUBLIME 텍스트 편집기에서 else문을 사용하는 대신 #RUN THE SCRIPT와 같다. if문이 참이라면 ?.py 스크립트가 직접 실행되고 있다는 걸 알기 때문이다.

def func():
	print("FUNC() IN ONE.PY")

def function():
	pass
def function2():
	pass

if __name__ == '__main__':
	function2()
    function()

주요 개념은 코드 조직화다.

함수와 클래스는 상단에서 정의하고, 코드를 실행하는 논리는 하단에서 정의한다.

큰 .py 스크립트에서 자주 보이는 흔한 구조다.

특히 모듈과 패키지를 사용하기 시작할 때

 

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
	return '<h1>Hello Puppy!</h1>'

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

decoration으로 해당 페이지를 웹 애플리케이션의 경로에 직접 연결한다.

 

@app.route('/information')
def info():
	return "<h1>Puppies are cute!</h1>"

spring에서의 mapping annotation과 비슷하다.

 

동적 라우팅 방법

@app.route('/some_page/<name>')
def other_page(name):
	#Later we will see how to use
    #this parameter with templates!
    return 'User: {}'.format(name)

@app.route('/puppy/<name>')
def puppy(name):
	return "<h1>This is a page for {}</h1>".format(name)

 

 

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('basic.html')

동일 레베의 디렉토리에서 templates라는 폴더를 찾고, 해당 폴더 안에서 basic.html을 찾는다.

 

@app.route('/')
def index():
	some_variable = "Jose"
    	return render_template('basic.html', my_variable=some_variable)
    
if __name__ == '__main__':
	app.run(debug=True)
    
    
    
 <body>
 	<h1>Hello! {{my_variable}}</h1>
 <body>

 

@app.route('/')
def index():
	name='Jose'
    	letters = list(name)
    	pup_dictionary = {'pup_name':'Sammy'}
    return render_template('basic.html',name=name, letters=letters, pup_dictionary=pup_dictionary)


<h1>{{letters}}</h1> 
<h1>{{letters[0]}}</h1>
<h1>{{letters[2:]}}</h1>
<h1>{{pup_dictionary}}</h1>
<h1>{{pup_dictionary['pup_name']}}</h1>

 

@app.route('/')
def index():
	mylist = [1,2,3,4,5]
    return render_template('basic.html', mylist=mylist)
    

<ul>
    {% for item in mylist %} # 제어 흐름 논리 명령문
    <li>{{item}}<li> # 변수 구문
    {% endfor %}
</ul>

 

728x90