728x90
Flask 기초
- virtual Environment - An isolated workspace for managing Python project dependencies independently.
- Anaconda 사용
conda create --name myvenv
- conda = invoke the Conda package manager.
- create = create a new environment
- --name = This flag specifies that you're about to provide the name of the new environment.
- myvenv = environment name
Flask Hello World
예시:
# Import the Flask class from the flask module
from flask import Flask
# Create an instance of the Flask class
# The argument __name__ helps Flask determine the root path of the application
app = Flask(__name__)
# Decorator to tell Flask what URL should trigger our function
@app.route('/')
def index():
# This function will be triggered when the user accesses the root URL ('/')
return '<h1>Hello World!</h1>' # Returns an HTML string to be displayed in the browser
# This is a Python built-in variable which evaluates to the name of the current module.
# If the module is being run (as opposed to being imported), its value will be "__main__".
if __name__ == '__main__':
# This means that we are running this module directly, and not importing it.
app.run() # Start the Flask development server
Web application Router
예시:
from flask import Flask
app = Flask(__name__)
# 127.0.0.1:5000
@app.route('/')
def index():
return '<h1>Hello Puppy!</h1>'
# 127.0.0.1:5000/information
@app.route('/information')
def info():
return '<h1>Puppies are cute!</h1>'
if __name__ == '__main__':
app.run()
Dynamic Rountes
- Dynamic Routes - enable URLs to have variable segments, which are then passed as parameters to the corresponding function.
예시:
from flask import Flask
app = Flask(__name__)
# Decorator with a dynamic route.
# The portion <name> in the route is a variable part,
# and it will be passed as an argument to the decorated function.
@app.route('/puppy/<name>')
def puppy(name):
# The name parameter will capture the dynamic part of the URL.
# For example, if the user visits '/puppy/Rex', then 'Rex'
# will be passed as the 'name' argument to this function.
# The formatted string will display the captured name in the
# resulting HTML page.
return '<h1>This is a page for {}<h1>'.format(name)
if __name__ == '__main__':
app.run()
Debug mode
- Debug mode - provides detailed error messages and allows for live code reloading during development.
- Also gives us access to a console in the browser!
예시:
# Never have debug=True for production apps!
app.run(debug=True)
Flask 라우팅 연습문제
- Make Puppy Latin name page
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/')
def index():
return "<h1>Welcome! Go to /puppy_latin/name to see your name in puppy latin!</h1>"
@app.route('/puppy_latin/<name>')
def puppylatin(name):
pupname = ''
if name[-1]=='y':
puppyname = name[:-1]+'iful'
else:
puppyname = name+'y'
return "<h1>Hi {}! Your puppylatin name is {} </h1>".format(name,puppyname)
if __name__ == '__main__':
app.run(debug=True)
Basic Templates
- Basic Templates - dynamic generation of HTML content using placeholders and control structures, stored in a "templates" folder.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
# Connecting to a template (html file)
# By default, Flask looks in a folder named 'templates' for the given filename.
return render_template('00-Basic-Template.html')
if __name__ == '__main__':
app.run(debug=True)
- Jinja templating - allows embedding Python variables directly into HTML files.
예시:
{{variable}}
HTML 예시:
<h1>Basic variable insert: {{name}}!</h1>
<!-- Recall that we set mylist=letters in the .py file. -->
<!-- You could use whatever variable names you want -->
<h1>List example: {{mylist}}</h1>
<!-- We can index the list as well -->
<h1>Indexing the list for the first letter: {{mylist[0]}}</h1>
<!-- We can also use dictionaries -->
<h1>Puppy name from dictionary: {{mydict['pup_name']}}</h1>
Python 예시:
@app.route('/advpuppy/<name>')
def adv_puppy_name(name):
letters = list(name)
pup_dict = {'pup_name':name}
return render_template('01-Template-Variables.html',
name=name,mylist=letters,mydict=pup_dict)
- Jinja grants access to control flow structures, such as for loops and if statements, within templates.
예시:
{% %}
예시:
# for loop
<ul>
{% for item in mylist %}
<li>{{item}}</li>
{% endfor %}
</ul>
# if statement
{% if item in list %}
<p>Found you in the list of item</p>
{% else %}
<p>Hmm, item isn't in this list.</p>
{% endif %}
Template Inheritance
- Template Inheritance - base templates to reuse and override specific sections of other pages, ensuring consistency and reducing redundancy.
예시:
# Base HTML
... original code ...
{% block content %}
{% endblock %}
... original code ...
Inheritance:
# other page
{% extends "04-base.html"%}
{% block content %}
<h1>This is the home page.</h1>
<h2>Go to /puppy/name</h2>
{% endblock %}
- Filters - change or format data in templates, don't need to be edited in Python
예시:
{{ variable | filter }} {{ name | capitalize }}
- url_for - generates URLs for view functions
예시:
{{ url_for('view_name') }} {{ url_for('index') }} # for static file {{ url_for('folder_name', file_name) }}
(수정중)
본 후기는 정보통신산업진흥원(NIPA)에서 주관하는 <AI 서비스완성! AI+웹개발 취업캠프 - 프론트엔드&백엔드> 과정 학습/프로젝트/과제 기록으로 작성되었습니다.
'코딩캠프 > AI 웹개발 취업캠프' 카테고리의 다른 글
[AI 웹개발 취업캠프] 26Day - 인공지능 소개 (0) | 2023.08.22 |
---|---|
[AI 웹개발 취업캠프] 25Day - AI OT (0) | 2023.08.21 |
[AI 웹개발 취업캠프] 24Day - FastAPI(4) (0) | 2023.08.18 |
[AI 웹개발 취업캠프] 23Day - FastAPI(3) (0) | 2023.08.17 |
[AI 웹개발 취업캠프] 23.08.17 과제 (0) | 2023.08.17 |