Streamlit project: easy to build and deploy personal blog site


insert image description here

1 Introduction

Hello everyone, welcome to my blog! In this article, I will introduce in detail how to use Streamlit, a powerful tool, to build a personal blogging website. If you are interested in data visualization, interactive applications and blog writing, then this article will definitely help you a lot.

1.1 Exploring Streamlit: Creating Interactive Applications Easily

First, let's get acquainted with Streamlit. Streamlit is an open-source Python library for data scientists and developers that lets you build interactive and highly customizable data applications in an easy way. Without tedious front-end development, you only need to use Python to write code, and you can quickly create interactive data visualization applications. Streamlit provides a wealth of components and layout options, allowing you to easily display data, interact with users, and share your results.

1.2 The most complete Streamlit tutorial column

In my column: The most complete Streamlit tutorial , I have shared a series of tutorials about Streamlit, taking you from scratch to master this tool. If you haven't learned about Streamlit yet, I suggest you read the following articles first to better understand what will be explained in this article:
Streamlit Explanation Column (1): Installation and Initial Application of
Streamlit Explanation Column (2): Building the first An Application of
Streamlit Explanation Column (3): Two Solutions to Build Multi-page
Streamlit Explanation Column (5): Exploring the Powerful and Flexible st.write() Function
Streamlit Explanation Column (6): Showing the Magic of Text
Streamlit Explanation Column (8) : Image, Audio and Video Magic

2 My personal blog site is online!

My personal blog site has been successfully launched! You can visit my blog site through the following link: Website link

2.1 A blog website integrated with intelligent TCM tongue diagnosis-Chinese e-diagnosis column

This blog site is a place to gather all my articles in the Smart TCM Tongue Diagnosis - Zhonge Diagnosis column. Here you can easily browse, read each column, and view the images and content in each article. The construction of this website is based on Streamlit technology, which allows me to build this interactive blog website in a simple way without too much front-end development.

insert image description here

2.2 Early preparations

Here you need to export your blog post, intimate CSDN provides us with the export function!

Click Export on the blog editing page → click Export as a MarkDown file
ps: This can also be used as a backup method for your blog

insert image description here
insert image description here
After exporting all your blogs, organize them into a folder, and the preliminary preparation is over!

2.3 Running with Streamlit Cloud

I deployed this blog site on Streamlit Cloud, which is an official service provided by Streamlit. With Streamlit Cloud, I am able to deploy my application directly to the cloud and share it with everyone. If you want to learn more about how to use Streamlit Cloud to run and deploy applications, I will explain in detail in the most complete Streamlit Tutorial column, so stay tuned!

I really look forward to everyone visiting my personal blog site and experiencing the interactivity and rich and varied content. If you are interested in Streamlit, data visualization and interactive applications, then this blog site will definitely bring you a lot.

3 knowledge point explanation

3.1 Implementing multiple pages: two options

In my personal blog site, I have adopted two different methods to realize the multi-page function, so that readers can browse and read different blog posts more conveniently. Below, I will briefly introduce these two solutions for you. If you want to learn more about the implementation details of each solution, you can go to my article: Streamlit Explanation Column (3): Two solutions to build multiple pages .
The first solution: use Session State to achieve multi-page interaction
In this solution, I use the Session State function of Streamlit to realize multi-page interaction through shared state. Each page corresponds to a different state, so that I can switch between different pages according to the user's selection and operation, and maintain the consistency of the page state. This method is suitable for relatively simple multi-page applications, and it is relatively simple to implement without additional URL routing settings.
The second solution: Streamlit built-in multi-page
Another method is to use the built-in multi-page function of Streamlit. The latest version of Streamlit already supports creating multiple pages and navigating through different buttons or links. I implemented multi-page switching by writing different functions for each page, and then calling the corresponding functions when the user clicks on different links. This approach is very practical for more complex multi-page applications, it allows you to organize your application structure more flexibly, and provides more customization options.

If you are interested in these two schemes, I strongly recommend you to read my article: Streamlit Explanation Column (3): Two schemes build multiple pages , in which I introduce the implementation steps and precautions of each scheme in detail. Whether you are a beginner or an experienced developer, this article will bring you useful guidance and inspiration.

3.2 Code explanation

The following is the code implementation of using Streamlit to build a personal blog website. First, let's look at the overall structure of the code:

# 导入所需的库
import streamlit as st
import os
import re
import requests
from PIL import Image
from io import BytesIO

# 获取当前路径
current_path = os.getcwd()

# ...(略去了其他导入和定义函数的部分)

# 主应用程序
def main():
    # 在侧边栏添加标题
    st.sidebar.title("博文选择")
    # 设置博文文件夹路径(相对于当前路径)
    markdown_folder = current_path + '/blog/'  # 修改为你的文件夹路径
    markdown_files = [file for file in os.listdir(markdown_folder) if file.endswith('.md')]

    # 创建博文选择的下拉列表
    selected_file = st.sidebar.selectbox("选择要阅读的博文", markdown_files)

    # 构建博文的完整文件路径
    file_path = os.path.join(markdown_folder, selected_file)
    
    # 调用创建博文页面函数
    blog_page(file_path)

if __name__ == "__main__":
    main()

Next, let's explain in detail the Streamlit knowledge points involved in the code block by block.

Import the required libraries
First, we imported the libraries we will use in the code, including Streamlit, os, re, requests, PIL (for processing images), BytesIO (for processing byte streams).

Get the current path
We use the os.getcwd() function to get the current working path, which will help us determine the path to the blog folder.

Read the content of the Markdown file
This part of the code defines a function read_markdown_file(file_path), which is used to read the content of the Markdown file. We use with open() to open the file, read the contents and return.

Split Markdown content by image link
This part of code defines a function split_markdown_by_images(markdown_content), which is used to split Markdown content into multiple parts by image link. We use regular expressions and string manipulation to achieve segmentation.

Create a blog post page
This part of the code defines a function blog_page(file_path), which is used to create a single blog post page. First, we set the page title using st.title(). We then take the filename and use st.write() to insert the post title.

Next, we call the previously defined function to read and display the Markdown content. We split the content into parts by determining if the row contains an image link. If it is an image link, we use the requests library to get the image and use st.image() to display the image on the page; otherwise, we use st.markdown() to display the text content in Markdown format.

Main Application
In the main application, we start by adding a header to the sidebar. Then, we set the blog post folder path and list all Markdown files in the folder. Using st.sidebar.selectbox() , we create a dropdown list that allows the user to select a blog post to read.

Finally, we construct the full file path of the blog post and call the previously defined function blog_page() to create the blog post page.

3.3 Implementation steps

Step 1: Install Streamlit
Before getting started, make sure you have Streamlit installed. If it is not installed, you can enter the following command on the command line:

pip install streamlit

Step 2: Prepare Markdown articles
First, you need to prepare your Markdown articles, which will become the content of your blog site. You can put these Markdown articles in a folder, such as "blog" folder.

Step 3: Write the Streamlit application
Now, let us write the Streamlit application step by step to create a personal blog site.

First, import the required libraries:

import streamlit as st
import os
import re
import requests
from PIL import Image
from io import BytesIO

Next, get the current path:

current_path = os.getcwd()

Define a function to read Markdown file content:

def read_markdown_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

Implement a function to split Markdown content by image links:

def split_markdown_by_images(markdown_content):
    parts = []
    current_part = ""
    lines = markdown_content.splitlines()

    for line in lines:
        if re.match(r'\!\[.*\]\(http[s]?://.*\)', line):
            if current_part:
                parts.append(current_part)
            parts.append(line)
            current_part = ""
        else:
            current_part += line + "\n"

    if current_part:
        parts.append(current_part)

    return parts

Function to create a blog post page:

def blog_page(file_path):
    st.title("蓝色是天的中医舌诊博客网站")

    # 获取博文标题
    markdown_title = os.path.splitext(os.path.basename(file_path))[0]
    st.write(f"## {
      
      markdown_title}")  # 插入博文标题

    # 读取并显示Markdown内容
    markdown_content = read_markdown_file(file_path)

    # 将Markdown内容按图片链接分割
    content_parts = split_markdown_by_images(markdown_content)

    for part in content_parts:
        if re.match(r'\!\[.*\]\(http[s]?://.*\)', part):
            image_url = re.search(r'\((http[s]?://.*)\)', part).group(1)
            response = requests.get(image_url)
            response = response.content
            bytes_io_obj = BytesIO()
            bytes_io_obj.write(response)
            img = Image.open(bytes_io_obj)
            st.image(img, use_column_width=True)
        else:
            st.markdown(part)

Finally, create the main application:

def main():
    st.sidebar.title("博文选择")
    markdown_folder = current_path + '/blog/'  # 修改为你的文件夹路径
    markdown_files = [file for file in os.listdir(markdown_folder) if file.endswith('.md')]

    selected_file = st.sidebar.selectbox("选择要阅读的博文", markdown_files)

    file_path = os.path.join(markdown_folder, selected_file)
    blog_page(file_path)

if __name__ == "__main__":
    main()

Step 4: Run the Streamlit application
Run the following command in the terminal to start your Streamlit application:

streamlit run your_app_name.py

Replace "your_app_name.py" with the filename where you saved your code. This will start a local server and display your personal blog site in the browser.

Step 5: Publish website
You can use Streamlit Cloud to publish your blog website to the Internet. Streamlit Cloud is a platform that allows you to share and distribute Streamlit applications. For specific publishing steps, you can find more information in my column.

This is the complete process of using Streamlit to build a personal blogging website. With this simple application, you can display your Markdown blog posts and images in a beautiful interactive interface, making readers more enjoyable to read your content. Not only that, but Streamlit also offers more customization options that you can further improve your blogging website.

I hope this article is helpful for those of you who want to use Streamlit to build a personal blogging website. Welcome to explore more features of Streamlit and create amazing interactive data applications!

3.4 Complete code

import streamlit as st
import os
import re
import requests
from PIL import Image
from io import BytesIO

# 获取当前路径
current_path = os.getcwd()

# 读取Markdown文件内容
def read_markdown_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

# 将Markdown内容按图片链接分割
def split_markdown_by_images(markdown_content):
    parts = []
    current_part = ""
    lines = markdown_content.splitlines()

    for line in lines:
        if re.match(r'\!\[.*\]\(http[s]?://.*\)', line):
            if current_part:
                parts.append(current_part)
            parts.append(line)
            current_part = ""
        else:
            current_part += line + "\n"

    if current_part:
        parts.append(current_part)

    return parts

# 创建博文页面
def blog_page(file_path):
    # 设置页面标题
    st.title("蓝色是天的中医舌诊博客网站")

    # 获取博文标题
    markdown_title = os.path.splitext(os.path.basename(file_path))[0]
    st.write(f"## {
      
      markdown_title}")  # 插入博文标题

    # 读取并显示Markdown内容
    markdown_content = read_markdown_file(file_path)

    # 将Markdown内容按图片链接分割
    content_parts = split_markdown_by_images(markdown_content)

    for part in content_parts:
        if re.match(r'\!\[.*\]\(http[s]?://.*\)', part):
            image_url = re.search(r'\((http[s]?://.*)\)', part).group(1)
            response = requests.get(image_url)
            response = response.content
            bytes_io_obj = BytesIO()
            bytes_io_obj.write(response)
            img = Image.open(bytes_io_obj)
            st.image(img, use_column_width=True)
        else:
            st.markdown(part)

# 主应用程序
def main():
    # 在侧边栏添加标题
    st.sidebar.title("博文选择")
    # 设置博文文件夹路径(相对于当前路径)
    markdown_folder = current_path + '/blog/'  # 修改为你的文件夹路径
    markdown_files = [file for file in os.listdir(markdown_folder) if file.endswith('.md')]

    # 创建博文选择的下拉列表
    selected_file = st.sidebar.selectbox("选择要阅读的博文", markdown_files)

    # 构建博文的完整文件路径
    file_path = os.path.join(markdown_folder, selected_file)
    
    # 调用创建博文页面函数
    blog_page(file_path)

if __name__ == "__main__":
    main()

4 Epilogue

Through this article, we have learned how to use Streamlit, a powerful tool, to build a personal blog site and display Markdown content and images in an interactive interface. Instead of tedious front-end development, we can focus on writing code in Python to create an elegant and feature-rich blogging platform.

Streamlit provides easy-to-use interface elements that allow us to quickly build interactive data applications to share our knowledge and insights with our readers. In the process of building a personal blog site, we explored knowledge points such as how to read the content of Markdown files, process image links, and create multi-page interactions. At the same time, we also learned how to publish our website to the Internet through Streamlit Cloud to share our content with more readers.

As technology continues to evolve, we are able to interact with our readers in more innovative and convenient ways. Using Streamlit, we can not only build personal blogs, but also create various interactive data applications to present complex data and insights to the public in an intuitive way.

In this information age, having a personalized blog site is an excellent way to share knowledge and exchange experiences. I encourage everyone to try Streamlit, present your ideas and insights to the world, and create a creative and interactive learning platform.

I hope this article can help you get started with Streamlit and explore the fun of building a personal blog site. Whether you're a data scientist, developer, or blogger, Streamlit can help you create stunning interactive apps. Let us leave our own footprints in the ocean of technology and create more exciting stories!

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46043195/article/details/132217471