[Python #10] [Django #3] 获取我的POST列表并显示在网页

pixabay

上期简单的尝试了下把我的STEEM信息投放到网页,今天把我的POSTS放到网页上吧。(#边学边写真难)

添加 URL

首先在blog目录下的 urls.py 添加相关url。用slug来判断并读取Views.py的posts类,用.as_view()来显示ListView。

from django.urls import path
from .views import main_view, posts

urlpatterns = [
    path('', main_view, name='my_home'),
    path('@<slug:account>/', posts.as_view(), name='posts'),
]

image.png

添加类到Views.py

因上面命名了post,所以在 Views.py文件加上相应的类,这个类继承django的ListView。
重定义get函数,这里我们用到 Services.py里的 blog 函数。

from .services import my_data, blogs

class posts(ListView):
    template_name = 'posts.html'
    context_object_name = 'all_posts'

    def get(self, request, *args, **kwargs):
        self.queryset = blogs(kwargs['account'])
        return super().get(request, *args, **kwargs)

image.png

获取 POST 列表

用 steem-python 库调用某人的post列表,填入到 Services.py

from steem import Steem

def blogs(account=str):
    s = Steem()
    blogs = s.get_blog(account, entry_id=0, limit=50)

    return blogs

image.png

创建模板

该创建网页模板了,创建一个叫 templates 的文件夹到 blog 文件夹同级别下,并在之下创建一个 posts.html网页文件。

$ mkdir templates
$ touch templates/home.html

之后在html文件写入如下:

<h1>My Steem Blog</h1>
    <ul>
        {% for post in all_posts %}
            <li><a href="https://www.steemit.com/@{{post.comment.author}}/{{ post.comment.permlink }}" target="_blank">{{ post.comment.title }}</a></li>
        {% endfor %}
    </ul>

image.png
意思就是从 Views.py 获取的目录反复用li标签渲染到页面。
还差一步,需要把 template 路径设置到 Settings.py

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

image.png

运行

运行本地服务器后在 URL 加 @june0620后缀访问,成功。
image.png

.
.
.
.
[Cookie 😅]
Python 3.7.4
Django 2.2.4
steem-python 1.0.1
goorm IDE 1.3

Sort:  

@june0620 transfered 1.0 KRWP to @krwp.burn. voting percent : 0.65%, voting power : 79.42%, steem power : 1847324.24, STU KRW : 1200.
@june0620 staking status : 50 KRWP
@june0620 limit for KRWP voting service : 0.1 KRWP (rate : 0.002)
What you sent : 1.0 KRWP
Refund balance : 0.9 KRWP [45041551 - 259196e521b115f970aeb7f048adf6b0eecb757d]

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 64386.10
ETH 3142.17
USDT 1.00
SBD 3.98