Ubuntu16.04 将 Flaskapp 部署到Heroku 上

版权声明:本文为博主原创文章,如若转载请注明出处 https://blog.csdn.net/tonydz0523/article/details/82707569

这回要把flask项目部署到 Heroku网站上,由于这样使用数据库会比较麻烦,要实现项目的功能我们要重新更改获取数据方式:
这里我们把策略改为:网页搜索 –> form获取股票代码 –> 爬虫爬取数据 –> 数据传输到网页 –> js可视化处理
这里写一个获取数据的脚本,全是以前写过的代码拼凑的,就不标注了

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

def crawl_data(stock_code):
    headers = {
        'Referer': 'http://quotes.money.163.com/',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36'
    }
    try:
        stock_code_new = ''
        if int(stock_code[0]) in [0, 2, 3, 6, 9]:
            if int(stock_code[0]) in [6, 9]:
                stock_code_new = '0' + stock_code
            elif int(stock_code[0]) in [0, 2, 3]:
                if not int(stock_code[:3]) in [201, 202, 203, 204]:
                    stock_code_new = '1' + stock_code
        if stock_code_new:
            stock_url = 'http://quotes.money.163.com/trade/lsjysj_{}.html'.format(stock_code)
            respones = requests.get(stock_url, headers=headers).text
            soup = bs(respones, 'lxml')
            start_time = soup.find('input', {'name': 'date_start_type'}).get('value').replace('-', '')    # 获取起始时间
            end_time = soup.find('input', {'name': 'date_end_type'}).get('value').replace('-', '')        # 获取结束时间
            download_url = "http://quotes.money.163.com/service/chddata.html?code={}&start={}&end={}&fields=TCLOSE;HIGH;LOW;TOPEN;".format(stock_code_new, start_time, end_time)
            data = requests.get(download_url, headers=headers)
            with open('static/stock.csv', 'wb') as f:                                 #保存数据
                for chunk in data.iter_content(chunk_size=10000):
                    if chunk:
                        f.write(chunk)
                        return True
    except:
        return False

def csv2data(stock_code):
    status = crawl_data(stock_code)
    if status:
        df = pd.read_csv('static/stock.csv', encoding='gbk', usecols=[0, 2, 3, 4, 5, 6])
        stock_name = df['名称'][0]
        del df['名称']
        header = [["<b>{}</b>".format(i)] for i in df.columns.tolist()]
        data = df.T.values.tolist()
        return data, stock_name, header
    else:
        return False, False, False

这样整个flask项目就完成了,此时我们着手部署.
先去heroku注册账号
这里是python部署官网教程:https://devcenter.heroku.com/articles/getting-started-with-python
国内可能打不开
安装heroku:
sudo snap install heroku --classic
没有snap的需要安装:
sudo apt install snapd
登入
heroku login

cd 到你项目的目录,然后进入虚拟环境
部署要用到gunicorn,于是安装:

pip install gunicorn

获取项目依赖环境:
pip freeze > requirements.txt
添加环境配置文件:

$ vim .gitignore
# 写入
# 你的虚拟空间名字
venv   
*.pyc
.DS_Store
.env

在你的项目中添加Procfile文件:

$ vim Procfile
# 
web: gunicorn run:app

使用 gunicorn 项目为 run文件中的app

部署:

$ git init # 初始化git
$ heroku create 你的app名字 
$ git add . # 添加项目到git
$ git commit -m 'Initial app boilerplate'
$ git push heroku master # 部署到heroku
$ heroku ps:scale web=1  # 使用一个 heroku "dyno" 运行你的项目 每个账号免费dyno有限制 ,可以花钱获取更多

这样就算部署完成了。。

更新代码并重新部署:

$ git status 
$ git add .  # 添加所有更改
$ git commit -m 'a description of the changes'
$ git push heroku master  # 上传部署

查找运行情况,debug:

heroku logs --tail

这里是我部署的flaskapp,感兴趣的可以看一下:https://stock-graph-app.herokuapp.com/

猜你喜欢

转载自blog.csdn.net/tonydz0523/article/details/82707569