vue2+Flask网站,轻松部署到免费主机Heroku(1)

我们的项目:vue2实例 -- 微信公众号阅读器已经大致成型了,丑媳妇总归要见公婆,那本文我们学习一下,如何部署到商用主机上去。很简单,前后10分钟就差不多了。
如果想体验更专业的、价格不高的VPS,看一下:Heroku以外,新的虚拟主机推荐 http://www.jianshu.com/p/a6319cc8f2c0

免费主机选择

国内的新浪云、阿里云、腾讯云等等,对个人都不太友好!免费一个月后,就开始收钱!数据库竟然按访问次数收费?!
那转向国外吧,对个人都比较友好,一般简单网站应用,在一定范围内一直是免费的。
我们选择Miguel Grinberg推荐的Heroku

Heroku数据库10000条以内免费,访问次数不限,运行时长550小时/月,无访问30分钟下线(影响不大,再次访问重启时间约10秒),国内访问速度还可以。

vue2+Flask网站,轻松部署到免费主机Heroku(1)_第1张图片
Heroku_logo.png

参考:
Flask之旅《Flask Web开发:基于Python的Web应用开发实战》
Flask + Gunicorn 部署到 Heroku服务器,sqlite数据库,loggins

步骤:

  1. 注册Heroku账号,并初始化
  2. Build前端vue,修改后端Flask配置
  3. 上传代码到Heroku
  4. 初始化数据库,你的网站成功在线运行!

1. 注册Heroku账号,并初始化

先注册一个账号:http://www.heroku.com
下载安装专属命令行Heroku_cli。提高效率,不使用也可以。

打开Windows命令行窗口CMD:

heroku login
heroku create XXX(指定名字或者省略,这里我们取名vue2)
cd vue2

2. Build前端vue,修改后端Flask配置

下面来准备我们的网站代码。

  • 前端:用npm编译
# 另外打开一个CMD窗口
cd /c/git/vue-tutorial
npm run build

# 下面是Log:
> [email protected] build C:\git\vue-tutorial
> node build/build.js

- building for production...cp: no such file or directory: static/*
Hash: f760d9d47392db11bd19
Version: webpack 1.14.0
Time: 9012ms
                                                  Asset       Size  Chunks             Chunk Names
                  static/js/app.d0a4a5b4a8482071b2f0.js    19.9 kB    2, 0  [emitted]  app
           static/fonts/fontawesome-webfont.674f50d.eot     166 kB          [emitted]
         static/fonts/fontawesome-webfont.af7ae50.woff2    77.2 kB          [emitted]
          static/fonts/fontawesome-webfont.fee66e7.woff      98 kB          [emitted]
             static/img/fontawesome-webfont.912ec66.svg     444 kB          [emitted]
             static/js/manifest.204777bcbc9088eaec4a.js  832 bytes       0  [emitted]  manifest
               static/js/vendor.794bd27fae98c19d43db.js     130 kB    1, 0  [emitted]  vendor
           static/fonts/fontawesome-webfont.b06871f.ttf     166 kB          [emitted]
    static/css/app.60ad69fc7a58d803592ee0f5d6a0d59d.css     132 kB    2, 0  [emitted]  app
         static/js/manifest.204777bcbc9088eaec4a.js.map    8.86 kB       0  [emitted]  manifest
           static/js/vendor.794bd27fae98c19d43db.js.map     997 kB    1, 0  [emitted]  vendor
              static/js/app.d0a4a5b4a8482071b2f0.js.map     115 kB    2, 0  [emitted]  app
static/css/app.60ad69fc7a58d803592ee0f5d6a0d59d.css.map     220 kB    2, 0  [emitted]  app
                                             index.html  702 bytes          [emitted]
···

# 会产生以下目录和文件:
c:/git/vue-tutorial/dist
    |--static/    # css/js/font/img目录,hash文件名
    |--index.html
  • 后端Flask:
    1. 新建Heroku运行文件Procfile,就一行。告诉Heroku,你的Flask启动文件和app实例名字
# /c/git/vue2/Procfile
web: gunicorn manage:app
  1. 复制前端编译后的代码(index.html、static/)到Flask目录
/c/git/vue2/app/templates/index.html
/c/git/vue2/app/static/  # 整个目录
  1. 修改manage.py,增加deploy命令,用于后台数据库的创建
#/c/git/vue2/manage.py(部分)
@manager.command
def deploy():
    """Run deployment tasks."""
      from flask_migrate import init, migrate, upgrade
      from app.models import User

    # migrate database to latest revision
      init()
      migrate()
      upgrade()

3. 上传代码到Heroku

上传前准备:

# .gitignore文件
过滤 migrations目录、*.sqlite文件
# 新建requirements.txt(Heroku服务器会自动安装这个文件内的python modules)保证有以下模块:
gunicorn==19.6.0
psycopg2==2.6.1
Flask-JWT==0.3.2
#你如果用了venv虚拟环境的话,一行命令就行:
venv/Scripts/activate
pip freeze > requirements.txt

现在,你的网站文件夹应该类似这样:


vue2+Flask网站,轻松部署到免费主机Heroku(1)_第2张图片
Heroku app directory.png

git上传到Heroku服务器:

git add .
git commit -m "init"
git push heroku master
# 以下是Log:
Counting objects: 28, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (26/26), done.
Writing objects: 100% (28/28), 84.59 KiB | 0 bytes/s, done.
Total 28 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: -----> Noticed cffi. Bootstrapping libffi.
remote:      $ pip install -r requirements.txt
。。。
remote:        Successfully installed Babel-2.3.4 Flask-JWT-0.3.2...
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing...
remote:        Done: 57.9M
remote: -----> Launching...
remote:        Released v8
remote:        https://vue2.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy.... done.
To https://git.heroku.com/vue2.git
   25b9dec..bb9e8e6  master -> master

4. 初始化数据库,你的网站成功在线运行!

Heroku用的是PostgreSQL数据库,SQLAlchemy可以让我们从本地Sqlite,无缝迁移到服务器端的任何类型数据库,太省心了!当然,只是数据库结构,数据本身不会。

打开命令行CMD:

heroku addons:add heroku-postgresql:hobby-dev
# 提升为主database,flask里访问:os.environ.get('DATABASE_URL')
heroku pg:promote heroku-postgresql
# 因为你运行命令,在heroku server上创建的目录、文件跟web app根本不在一个环境里。所以,db migration三条命令(init/migrate/uprade)必须在Bash里一并运行完,不能一条条运行
heroku run python manage.py deploy
# 以下是Log:
2016-12-27T05:06:09.616209+00:00 app[api]: Starting process with command `python manage.py deploy` by user [email protected]
2016-12-27T05:06:13.552307+00:00 heroku[run.8366]: Starting process with command `python manage.py deploy`
2016-12-27T05:06:14.227293+00:00 heroku[run.8366]: State changed from starting to up
2016-12-27T05:06:17.673787+00:00 app[run.8366]: Creating directory /app/migrations ... done
2016-12-27T05:06:17.673914+00:00 app[run.8366]: Creating directory /app/migrations/versions ... done
2016-12-27T05:06:17.674315+00:00 app[run.8366]: Generating /app/migrations/README ... done
2016-12-27T05:06:17.674607+00:00 app[run.8366]: Generating /app/migrations/env.py ... done
2016-12-27T05:06:17.674921+00:00 app[run.8366]: Generating /app/migrations/env.pyc ... done
2016-12-27T05:06:17.675243+00:00 app[run.8366]: Generating /app/migrations/script.py.mako ... done
2016-12-27T05:06:17.684657+00:00 app[run.8366]: Generating /app/migrations/alembic.ini ... done
2016-12-27T05:06:17.684703+00:00 app[run.8366]: Please edit configuration/connection/logging settings in '/app/migrations/alembic.ini' before proceeding.
2016-12-27T05:06:17.778841+00:00 app[run.8366]: INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
2016-12-27T05:06:17.779862+00:00 app[run.8366]: INFO [alembic.runtime.migration] Will assume transactional DDL.
2016-12-27T05:06:17.792777+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added table 'mps'
2016-12-27T05:06:17.793905+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added index 'ix_mps_sync_time' on '['sync_time']'
2016-12-27T05:06:17.794082+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added table 'users'
2016-12-27T05:06:17.794297+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added index 'ix_users_username' on '['username']'
2016-12-27T05:06:17.795458+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added table 'articles'
2016-12-27T05:06:17.795703+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added index 'ix_articles_timestamp' on '['timestamp']'
2016-12-27T05:06:17.796452+00:00 app[run.8366]: INFO [alembic.autogenerate.compare] Detected added table 'subscriptions'
2016-12-27T05:06:17.818431+00:00 app[run.8366]: Generating /app/migrations/versions/90bab11f5f2b_.py ... done
2016-12-27T05:06:17.875455+00:00 app[run.8366]: INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
2016-12-27T05:06:17.875507+00:00 app[run.8366]: INFO [alembic.runtime.migration] Will assume transactional DDL.
2016-12-27T05:06:17.881030+00:00 app[run.8366]: INFO [alembic.runtime.migration] Running upgrade -> 90bab11f5f2b, empty message
2016-12-27T05:06:18.191142+00:00 heroku[run.8366]: Process exited with status 0
2016-12-27T05:06:18.203898+00:00 heroku[run.8366]: State changed from up to complete

这时打开Heroku网站,你能看到自己的app仪表盘:


vue2+Flask网站,轻松部署到免费主机Heroku(1)_第3张图片
Heroku Postgres.png

最后,配置一些环境变量env. vars:

  • DATABASE_URL 是自动创建的,给SQLAlchemy提供数据库地址
  • FLASK_CONFIG=heroku 是给Flask配置用的
vue2+Flask网站,轻松部署到免费主机Heroku(1)_第4张图片
Heroku env. vars.png

全部准备完毕,让我们的网站上线吧!

heroku ps:scale web=1
heroku open
heroku logs -t

BINGO!可以访问啦

点一下试试 --> Vue2.0实例--微信公众号阅读器 http://vue2.heroku.com/

点击注册,可以成功记录用户注册信息到数据库了吧?登录也没问题了,OK!

项目源码

Tips

  • 有时Heroku run bash会出现ECONNRESET错误!
    一般是由于Firewall或代理引起的,可以后台运行:
c:\git\vue2>heroku run:detached python manage.py deploy
Running python manage.py deploy on vue2... done, run.8366 (Free)
Run heroku logs --app vue2 --dyno run.8366 to view the output.
  • Heroku在国外,有时用爬虫requests -> Beautifulsoup时,会乱码,需要手动设置lang/type。
    requirement.txt,也要加入 lxml==3.6.4
user_agent = {
    'User-agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.0 Chrome/30.0.1599.101 Safari/537.36',
    'Accept-Language': 'zh-CN',
    'Content-Type': 'charset=UTF-8'
    }

网站统计

免费的可以用Baidu统计:http://tongji.baidu.com/
在网站index.html里,中间,加一段js代码就行,很方便。



    简读 - 微信公众号阅读器RSS

    
        

Baidu统计 设置里,网站首页填:vue2.heroku.com/

如果数据超限(大于10000条),怎么删除,请看第二篇:http://www.jianshu.com/p/f7e670b2c873
Flask网站轻松部署到免费主机Heroku(3) - 多平台 Multiple Buildp...
http://www.jianshu.com/p/5236ca08275d

你可能感兴趣的:(vue2+Flask网站,轻松部署到免费主机Heroku(1))