Try   HackMD

如何利用pelican 建立自己的blog

Date: 2017-01-20 11:54

tags: python

費了一番功夫總算是把blog 架起來了,在新的blog上紀錄一下。

2024-10-25 :此篇已經太舊,當廢文看看就好

Q1:為什麼不用Jkelly?
A1:我大Python神教無所畏懼。(不會用Ruby orz)
Q2:為什麼不用現成的就好?(像是logdown,wordpress,wix)
A2:考量到Blog服務可能會以各種原因停止運作, 最好所有的文檔案圖片可以self-hosted,目前考慮把Hackmd當markdown editor,所有筆記檔案(markdown, oneNote, Apple Note)和廢文轉成markdown儲存在github上,以github io釋出。
另外Desktop推薦joplin,可以匯入oneNote, markdown, Apple Notes(要先轉成markdown)。
joplin可以跨主流裝置(ios, ipad, Android, Linux ,MacOS),可以self-hosted,還可以接入Ollama。

目前手上匯入joplin的文章已經過時或過舊,大部分要重寫,整理後再逐步釋出。

enviroment

pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

start!

首先當然是要安裝pelican

pip install pelican Markdown typogrify feedgenerator jinja2 pygments docutils pytz blinker unidecode six MarkupSafe python-dateutil

透過pelican-quickstart 建立我們的project

pelican-quickstart  

就會在我們的project中看就以下結構的專案檔

yourproject/
├── content
│   └── (pages)
├── output
├── develop_server.sh
├── fabfile.py
├── Makefile
├── pelicanconf.py       # 主設定檔
└── publishconf.py       # 發布用設定檔

接著下載佈景 挑一個順眼的即可
筆者是使用boostrap3

get themes

git clone --recursive https://github.com/getpelican/pelican-themes ~/pelican-themes

pelican-plugins要複製至剛剛建立的pelican project中

get pelican-plugins

git clone https://github.com/getpelican/pelican-plugins

設定主設定檔

用editor 打開pelicanconf.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Last modified: 2017-01-23 11:14:58

from __future__ import unicode_literals

AUTHOR = 'splasky' #修改成自己的名稱
SITENAME = u'Splasky Site' #blog 名稱
SITEURL = '' #沒有domain name 不填寫

PATH = 'content' # content位置
THEME = '../pelican-themes/pelican-bootstrap3' #你的佈景位置
PLUGIN_PATHS = ['pelican-plugins'] #plugin位置
JINJA_ENVIRONMENT = {"extensions": ['jinja2.ext.i18n']}
STATIC_PATHS = ['images', 'files', 'extra/robots.txt', 'extra/favicon.ico']
EXTRA_PATH_METADATA = {
    'extra/robots.txt': {'path': 'robots.txt'},
    'extra/favicon.ico': {'path': 'favicon.ico'},
}

# Feed setting
FEED_ALL_ATOM = 'feeds/all.atom.xml'
FEED_ALL_RSS = 'all-posts'

# Template settings
DISPLAY_PAGES_ON_MENU = True
DISPLAY_CATEGORIES_ON_MENU = True

DIRECT_TEMPLATES = ('index', 'categories', 'authors', 'archives', 'search')


# sitemap configure
SITEMAP = {
    "format": "xml",
    "priorities": {
        "articles": 0.7,
        "indexes": 0.5,
        "pages": 0.3,
    },
    "changefreqs": {
        "articles": "monthly",
        "indexes": "daily",
        "pages": "monthly",
    }
}

TIMEZONE = 'Asia/Taipei' #時區

DEFAULT_LANG = 'zh-tw' #language
DEFAULT_DATE_FORMAT = '%b %d, %Y' #date format

# Search
SEARCH_BOX = True

# Sharing
FACEBOOK_LIKE = True
TWITTER_LATEST_TWEETS = True
TWITTER_FOLLOW_BUTTON = True
TWITTER_TWEET_COUNT = 3
TWITTER_SHOW_REPLIES = 'false'
TWITTER_SHOW_FOLLOWER_COUNT = 'true'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
         ('Python.org', 'http://python.org/'),
         ('Jinja2', 'http://jinja.pocoo.org/'),
         ('pelican-boostrap3', 'https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3'),
         ('Pelican plugins', 'https://github.com/getpelican/pelican-plugins'),
         )

# Social widget
SOCIAL = (('reserved', '#'),
          )

DEFAULT_PAGINATION = 10

# Uncomment following line if you want document-relative URLs when developing
# RELATIVE_URLS = True

# Themes
GITHUB_URL = 'https://github.com/splasky'
DISQUS_SITENAME = u'splasky' #DISQUS留言板設定
TAG_CLOUG_MAX_ITEMS = 20

# Plugins
PLUGINS = ['summary',
           'liquid_tags.img',
           'liquid_tags.video',
           'liquid_tags.include_code',
           'liquid_tags.notebook',
           'liquid_tags.literal',
           'i18n_subsites',
           'tag_cloud',
           'tipue_search',
           'related_posts']

RELATED_POSTS_MAX = 10
RELATED_POSTS_SKIP_SAME_CATEGORY = True

# Artical
ARTICLE_URL = 'blog/{date:%Y}-{date:%m}-{date:%d}/{slug}'
ARTICLE_SAVE_AS = 'blog/{date:%Y}-{date:%m}-{date:%d}/{slug}.html'
PAGE_URL = '{date:%Y}-{date:%m}-{date:%d}/{slug}'
PAGE_SAVE_AS = '{date:%Y}-{date:%m}-{date:%d}/{slug}.html'
TAG_URL = 'tags/{slug}'
TAG_SAVE_AS = 'tags/{slug}.html'
#  TAGS_URL = 'tags'

#利用boostrap3 所提供的功能
# pelican-bootstrap3 extras
SHOW_ARTICALE_CATEGORY = True
USE_PAGER = True
BANNER = 'images/sunset-1645103_1920.jpg'
SITELOGO = "favicon.ico"
FAVICON = 'favicon.ico'
DISPLAY_TAGS_ON_SIDEBAR = True
DISPLAY_CATEGORIES_ON_SIDEBAR = True
DISPLAY_RECENT_POSTS_ON_SIDEBAR = True
DISQUS_DISPLAY_COUNTS = True
ADDTHIS_PROFILE = True
DISPLAY_BREADCRUMBS = True
SEARCH_URL = '/blog/search.html'

發佈

pelican 本身就有提供很好用的makefile 來協助我們發布或測試

$make help
Makefile for a pelican Web site                                           
                                                                          
Usage:                                                                    
   make html                           (re)generate the web site          
   make clean                          remove the generated files         
   make regenerate                     regenerate files upon modification 
   make publish                        generate using production settings 
   make serve [PORT=8000]              serve site at http://localhost:8000
   make serve-global [SERVER=0.0.0.0]  serve (as root) to :80    
   make devserver [PORT=8000]          start/restart develop_server.sh    
   make stopserver                     stop local server                  
   make ssh_upload                     upload the web site via SSH        
   make rsync_upload                   upload the web site via rsync+ssh  
   make dropbox_upload                 upload the web site via Dropbox    
   make ftp_upload                     upload the web site via FTP        
   make s3_upload                      upload the web site via S3         
   make cf_upload                      upload the web site via Cloud Files
   make github                         upload the web site via gh-pages   
                                                                          
Set the DEBUG variable to 1 to enable debugging, e.g. make DEBUG=1 html   
Set the RELATIVE variable to 1 to enable relative urls                    

接著於github建立一個repository 並建立push的分支

git add remote [xxxxxx]
git push -u origin master

最後在我們的目錄下將blog整個push上去

make github

接折進到自己的repository將github pages 切換為gh-pages

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

最後就完成了

利用pelican 寫文章

pelican 支援reStructuredText 格式和markdown格式,因為我比較熟markdown所以就用markdown。
如果想學markdown可以參考markdown tw

建立第一個md file

Title: My super title 標題
Date: 2010-12-03 10:20 日期
Modified: 2010-12-05 19:30 修改日期
Category: Python 分類
Tags: pelican, publishing 標籤
Slug: my-super-post 小標
Authors: Alexis Metaireau, Conan Doyle 作者
Summary: Short version for index and feeds

內文
This is the content of my super blog post.

code identifier

:::python
printf "hello"

:::python
printf "hello"

To display line numbers, use a path-less shebang instead of colons:

#!python
print("The path-less shebang syntax will show line numbers.")

#!python
print("The path-less shebang syntax *will* show line numbers.")
print("Good loli")
print("123")

自動連結

<連結>

標記一小段行內程式碼

用反引號把它包起來(`)
Use the printf() function.

刪除線:

delete

<s>delete</s>

Linking to static file

假設我們的 project長這樣

website/
├── content
│   ├── category/
│   │   └── article1.rst
│   ├── article2.md
│   └── pages
│       └── about.md
└── pelican.conf.py

如果我們要連結md files

The first article
#################

:date: 2012-12-01 10:02

See below intra-site link examples in reStructuredText format.

`a link relative to the current file <{filename}../article2.md>`_
`a link relative to the content root <{filename}/article2.md>`_

article2.md:


Title: The second article
Date: 2012-12-01 10:02

See below intra-site link examples in Markdown format.

[a link relative to the current file]({filename}category/article1.rst)
[a link relative to the content root]({filename}/category/article1.rst)

Linking to static files

當我們要連結非文章或是pages時,我們需要在該路徑前面加上一個{filename}告訴pelican要從哪裡複製和連結該靜態檔案。

假設我們要在這樣的project連結靜態檔

content
├── images
│   └── han.jpg
├── pdfs
│   └── menu.pdf
└── pages
    └── test.md
test.md would include:
![Alt Text]({filename}/images/han.jpg)
[Our Menu]({filename}/pdfs/menu.pdf)

要在pelicanconf.py中宣告

STATIC_PATHS = ['images', 'pdfs']

最後就會在output複製該文件(image,pdfs) 便建立連結於test.md中。

Attaching static files

附加檔案:前綴{attach}
For example, a project’s content directory might be structured like this:


content
├── blog
│   ├── icons
│   │   └── icon.png
│   ├── photo.jpg
│   └── testpost.md
└── downloads
    └── archive.zip

pelicanconf.py would include:


PATH = 'content'
STATIC_PATHS = ['blog', 'downloads']
ARTICLE_PATHS = ['blog']
ARTICLE_SAVE_AS = '{date:%Y}/{slug}.html'
ARTICLE_URL = '{date:%Y}/{slug}.html'
testpost.md would include:

Title: Test Post
Category: test
Date: 2014-10-31

![Icon]({attach}icons/icon.png)
![Photo]({attach}photo.jpg)
[Downloadable File]({attach}/downloads/archive.zip)
Site generation would then produce an output directory structured like this:

output
└── 2014
    ├── archive.zip
    ├── icons
    │   └── icon.png
    ├── photo.jpg
    └── test-post.html

Linking to authors, categories, index and tags

authors,{author}name
categories, {category}foobar
index ,{index}
tagname ,{tag}

add juypter notebook

  • Create a Jupyter notebook with some basic content.
  • Create a file that has the same name as your notebook, but with the extension .ipynb-meta.
  • Add the following content to the ipynb-meta file, but change the fields to match your own post:
Title: First Post
Slug: first-post
Date: 2016-06-08 20:00
Category: posts
Tags: python firsts
author: Vik Paruchuri
Summary: My first post, read it to find out.

建立網站中遇到的問題

  • 為什麼留言板出不來?

可能是佈景主題的html有問題 因為github要求所有的連結都必須是https,可以打開broswer檢查

  • search 功能會出錯

修改pelicanconf.py 的SEARCH_URL = '/你的repository/search.html'

參考資料

使用 Pelican 建立 blog
Pelican doc