촬리의늘솔길

flask 실습 본문

✍~2022/클라우드

flask 실습

리촬리 2022. 1. 20. 13:36

pip install virtualenv 여러군데 공유하고 작업할 수 있게 기능을 터미널을 이용해 깔아줌

virtualenv env

액티베이트 환경 설정

\env\Scripts\activate.bat

어우 이거 안되어가지고는 스택오버플로우 당근찾아줌

다음. fpip3 install flask flask-sqlalchemy 쳐줌

플라스크가깔아짐

 

from flask import Flask
app = Flask(__name__)

@app.route('/')

def index():
    return "Hello, world!"

   


if __name__ == "__main__":
    app.run(debug=True)
 
왜 매번 해도 매번 까먹는건지...복습좀하자..
 
근데 솔직히 css는 부트..그거 있잖어 코드스니펫
body{
    margin :0;
    font-family : sans-serif;
}
 
 index.html
{% extends 'base.html' %}

{% block head %}



{% endblock%}



{% block body %}

<h1>Template</h1>

{% endblock %}

진자 활용하여 css파일 링크연결

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel ="stylesheet" href = "{{ url_for('static',filename='css/') }}"
    {% block head %}{% endblock%}
</head>
<body>
    {% block body %}{% endblock%}
</body>
</html>​
 
 
오 처음배우는 Mysql(db)
 or Postgres, or 
쨌든 검색해보고..알아보래
 
forward slashes is an absolute path, 
Three is a relative path, we want a relative path here,
because I don't want to have to specify an exact location,
I just want it to reside in the project location.
test.db를 부른다
모든것이 저장된다 test.db file 에 
nullable이뭐지 (null에 할당할 수 있는 값 형식) 
사용이유: we don't want this to be left blank, we dont want the user to be able to create a new task, and then just leave the content of that task empty
 
return task 
 
pip3 install flask-SQLAlchemy
 
꼭 깔아주기..
 
db생성
>>> from app import db
>>> db.create_all()

 
 
 
>>> exit()
 
 
 
 
 
 
 
 
---
Heroku
서버 갖게해주는..
 
 
from flask import Flask , render_template ,url_for,request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy.orm import exc
from werkzeug.utils import redirect
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI' ]= 'sqlite:///test.db'

db = SQLAlchemy(app)
db.create_all()

class Todo(db.Model):
    
    id = db.Column(db.Integer,primary_key = True)
    content = db.Column(db.String(200), nullable = False)
    date_created = db.Column(db.DateTime,default = datetime.utcnow)

    def __repr__(self):
        return '<Task %r>' % self.id
@app.route('/', methods = ['POST','GET'])

def index():
    if request.method == 'POST':
        task_content = request.form['content']
        new_task = Todo(content = task_content)
        
        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect('/')
        except:
            return 'There was an issue adding your task'

    else:
        
        tasks = Todo.query.order_by(Todo.date_created).all()
        return render_template('index.html', tasks = tasks)

  

@app.route('/delete/<int:id>')
def delete(id):
    task_to_delete = Todo.query.get_or_404(id)

    try:
        db.session.delete(task_to_delete)
        db.session.commit()
        
        return redirect('/')
    except:
        return 'There was a problem deleting that task'

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    task = Todo.query.get_or_404(id)
    if request.method == 'POST':
        task.content = request.form['content']
        try:
            db.session.commit()
            return redirect('/')
        except:
            return 'There was an issue updating your task'
    else:
        return render_template('update.html', task=task)

if __name__ == "__main__":
    app.run(debug=True,host ='0.0.0.0',port = 5000)
 
 
 
감격..비록 기능은 없어진 flask 웹이지만,,연결성공

 

 

gce오류난거 해결

sudo apt-get install python-setuptools python-dev build-essential

sudo easy_install pip

sudo pip install flask

sudo python app.py

 

순서대로 쳐 주면 끝:)

https://philosopher-chan.tistory.com/467

 

GCP Flask 배포

일단은 GCP 콘솔로 들어갑니다. https://console.cloud.google.com/home/dashboard?hl=ko&project=evocative-lodge-266710 Google Cloud Platform 하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을..

philosopher-chan.tistory.com

---
 
 
부족한점 :
css,html 기본 문법
flask 기본 문법, 가상환경 구동법 
jinja
익숙하지가 않음. 했던거 다까먹음 진짜.. 내것으로 만들기 이번 방학의 목표

 

728x90

'✍~2022 > 클라우드' 카테고리의 다른 글

kibana  (0) 2022.08.11
ELK-2(ElasticSearch)  (0) 2022.08.09
ELK -DAY1  (0) 2022.08.08
도커 공부  (0) 2022.01.16
클라우드 부트캠프 - (1)  (0) 2022.01.08