Wei-Ting
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: python --- # DAY 29 Django部署應用程式 ## 建立Heroku帳號 首先先去 https://heroku.com/ 辦帳號,Heroku辦帳號是免費的,只要點sign up 就可以辦了 ![](https://i.imgur.com/0jByIWM.png) ## 安裝Heroku Toolbelt 要在Heroku伺服器上部署和管理專案,我們需要用到Heroku Toolbelt中所提供的工具,我們需要在虛擬環境中輸入```pip install dj-database-url```、```pip install dj-static```、```pip install static3```和```pip install gunicorn``` 一定要照順序逐個執行這些指令,這樣我們就會知道哪些套件未能安裝,dj-database-url套件能協助Django與Heroku使用的資料庫進行溝通 ## 建立requirements.txt放入套件清單 Heroku需要了解我們專案是依賴哪些套件,因此我們會用pip來生成一個檔案,在其中列出這些套件清單,首先啟動虛擬環境後輸入```pip freeze > requirements.txt```命令,freeze命令能讓pip把專案中目前安裝的所有套件名稱都寫入requirements.txt檔中,接著我們開啟這個txt檔案看看,然後在裡面新增下圖紅色框框的內容,新增的psycopg2能協助Heroku管理作用中的資料庫,如下 ![](https://i.imgur.com/V5k0iQN.png) ## 指定python版本 如果沒有指定python的版本,Heroku會使用目前python的預設版本,所以我們要先確定我們使用的python版本,我們要先在虛擬環境裡輸入```python --version```命令,我們就會看到它顯示的python版本,我們在這是用python3.7.0的版本,接下來我們要在manage.py所在的資料夾中建立一個runtime.txt檔,並輸入以下內容來指定python版本 ![](https://i.imgur.com/bktak0u.png) ## 修改setting.py來部署到Heroku 我們要開啟setting.py然後在最後面的位置加入一個部分來定義Heroku環境相關設定,如下 ```python= cwd = os.getcwd() # 取得工作目錄 if cwd == '/app' or cwd[:4] == '/tmp': import dj_database_url # 匯入dj_database_url用在Heroku上來配置伺服器 DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } # 支援HTTPS的請求 SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # 確保Django會從Heroku的URL中尉專案提供服務 ALLOWED_HOSTS = ['learning-log-final.herokuapp.com'] DEBUG = False # 設定專案讓它能在Heroku上正確提供靜態檔 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) ``` ## 建立Procfile來啟動處理程序 Procfile會告訴Heroku啟動哪些處理程序來正確地位專案提供服務,建立一個Procfile(P一定要大寫)檔案,不用設副檔名,存在和manage.py同一個資料夾中,檔案內容如下 ``` web: gunicorn learning_log.wsgi --log-file - ``` 這行程式告訴Heroku使用gunicorn作為伺服器,並使用learning_log資料夾中的wsgi.py中的設定來啟動應用程式 ## 修改Heroku的wsgi.py檔 我們匯入了能幫助正確提供靜態檔案的Cling,並用來啟動應用程式 ```python= import os from django.core.wsgi import get_wsgi_application from dj_static import Cling # 新增區塊 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') # 新增區塊 application = Cling(get_wsgi_application()) ``` ## 為靜態檔製作一個目錄 在Heroku上Django會集合所有的靜態檔並放在一個地方,這樣能提高管理和運用的效率,我們會建立一個存放靜態檔案的目錄,在learning log/learning log/static的資料夾內,新增一個placeholder.txt,內容如下 ``` This file ensures that learning_log/static/ will be added to the project. Django will collect static files and place them in learning_log/static/. ``` ## 使用Git來追蹤檔案 Git是個版本控制程式,能讓我們每次成功時做出新功能時擷取專案程式碼的快照來備存,不論出現甚麼問題,都可以輕鬆還原到最新可用的那一個快照紀錄,每個快照都稱為commit ### 安裝Git Heroku Toolbelt含有Git在其中,因此它應該已經安裝在系統內了,執行```git --version```命令,可以看到現在的版本 ### 配置Git Git可追蹤是誰修改了專案,就算專案只有一個人開發也是這樣的情況,若要開始記錄追蹤專案,Git會需要我們的名稱和email ```(learning_log) C:\Users\ASUS\learning_log>git config --global user.name "weiting"``` ```(learning_log) C:\Users\ASUS\learning_log>git config --global user.email "b22379222@gmail.com"``` ### 提交專案 1. 執行```git init```命令,在learning log專案所在的目錄中初始化一個空的倉庫 2. 我們執行```git add .```命令,這會把未被忽略的檔案新增到這個倉庫中 3. 執行```git commit -am "Ready for deployment to heroku"```命令,其中-a旗標是讓Git在這個提交中放入所有修改過的檔案,-m旗標會讓Git記錄一條log訊息 4. 執行```git status```命令,輸出指出目前位在master分支中,而工作目錄是乾淨的 ## 推送到Heroku 1. 執行```heroku login```來登入Heroku 2. 執行```heroku create```建立一個空專案 3. 執行```git push heroku master```命令讓Git把專案的master分支推送到Heroku剛才建立的倉庫中,Heroku會使用這些檔案在伺服器上建置專案,然後列出用來存取這個專案的URL 4. 執行```heroku ps```命令會看到專案處於作用中的狀態 5. 執行```heroku open```命令能免除開啟瀏覽器並輸入Heroku給定的URL ## 在Heroku上建置資料庫 我們需要執行一次遷移來設定即時資料庫,並套用我們在開發過程中生成的所有遷移,要對Heroku專案執行Django和Python的命令,可使用heroku run命令,執行```heroku run python manage.py migrate```命令,在這裡Django套用預設的遷移和我們在開發learning log期間生成的遷移 --- 好了~我們的Django實作部分如期的在十天內結束了:confetti_ball:,IT的30天也差不多到了結尾,明天會最後一篇會打這30天的心得感想 #### 今天結束,各位明天見 :hand: *** 資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully