【Typora】基于python3实现CSDN图床

命运对每个人都是一样的,不一样的是各自的努力和付出不同,付出的越多,努力的越多,得到的回报也越多,在你累的时候请看一下身边比你成功却还比你更努力的人,这样,你就会更有动力。

导读:本篇文章讲解 【Typora】基于python3实现CSDN图床,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

技术背景

写博客既想在typora这款软件上写,又想将图片传到云上。之前也使用过Github + Picgo + Typora实现

核心代码

基于python3实现实时上传图片到CSDN上

# -*- coding: UTF-8 -*-
'''
@文件        :csdnUpload.py
@时间        :2023/3/30 23:48:46
@作者        :Alan
@版本        :2.0
@说明        :Typora利用csdn作为图床
'''
from __future__ import print_function
import random
from io import BytesIO
import sys
from PIL import Image
import os
from threading import Thread
import psutil
import re
import requests
import http.cookiejar as cookielib
import time
import requests
from requests_toolbelt import MultipartEncoder
import ctypes

os.chdir(os.path.expanduser('~'))  # 这是打包版本的代码
requests.packages.urllib3.disable_warnings()
session = requests.session()


class show_code(Thread):
    def __init__(self, url):
        Thread.__init__(self)
        self.url = url

    def run(self):
        response = requests.get(self.url)
        img = Image.open(BytesIO(response.content))  # 打开图片,返回PIL image对象
        img.show()


def IsLogin():
    '''
    文件读取cookie,检测cookie是否合法。
    '''
    try:
        session.cookies = cookielib.LWPCookieJar(filename=".cookie/csdn.txt")
        session.cookies.load()

        # 修改地方
        url = "https://imgservice.csdn.net/direct/v1.0/image/upload?type=blog&rtype=markdown&x-image-template=&x-image-app=direct_blog&x-image-dir=direct&x-image-suffix=png"
        response = session.get(url)
        if response.json()['msg'] == "success":
            return True
        else:
            return False
    except Exception as e:
        return False


def Login():
    '''
    csdn自动登录,同时保存cookie
    '''
    response = session.get(
        'https://open.weixin.qq.com/connect/qrconnect?appid=wx0ae11b6a28b4b9fc&scope=snsapi_login&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Fv1%2Fregister%2FpcAuthCallBack%3FpcAuthType%3Dweixin&state=csdn&login_type=jssdk&self_redirect=default&style=white&href=https://csdnimg.cn/release/passport/history/css/replace-wx-style.css',
        verify=False)
    uuid = re.findall(
        '<img class="qrcode lightBorder" src="(.*?)"', response.text)[0]
    img_url = 'https://open.weixin.qq.com' + uuid
    t = show_code(img_url)
    t.start()
    t.join()

    uuid = uuid.split('/')[-1]
    url = 'https://lp.open.weixin.qq.com/connect/l/qrconnect?uuid=' + uuid
    while True:
        response = session.get(url, verify=False)
        code = re.findall("window.wx_code='(.*?)'", response.text)
        if code != ['']:
            for proc in psutil.process_iter():  # 遍历当前process
                try:
                    if proc.name() == "Microsoft.Photos.exe":
                        proc.kill()  # 关闭该process
                except Exception as e:
                    pass
            break
        time.sleep(0.5)

    url = 'https://passport.csdn.net/v1/register/pcAuthCallBack?pcAuthType=weixin&code=%s&state=csdn' % code[0]
    session.get(url)
    session.cookies.save()
    IsLogin()


def UploadPic(picList: list):
    '''
    图片上传
    '''

    for pic in picList:
        # 获得图片授权
        url = "https://imgservice.csdn.net/direct/v1.0/image/upload?type=blog&rtype=markdown&x-image-template=&x-image-app=direct_blog&x-image-dir=direct&x-image-suffix=png"
        resopnse = session.get(url)
        key = resopnse.json()['data']
        upload_url = key['host']
        fields = {
            'key': key['filePath'],
            'policy': key['policy'],
            "OSSAccessKeyId": key['accessId'],
            "success_action_status": "200",
            "signature": key['signature'],
            "callback": key['callbackUrl'],
            'file': (os.path.basename(pic), open(pic, 'rb'), "image/png"),
        }
        multipart_encoder = MultipartEncoder(
            fields, boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1)))
        headers = {
            'content-Type': multipart_encoder.content_type,
        }
        res = requests.post(upload_url, headers=headers,
                            data=multipart_encoder, verify=False)
        if (res.status_code == 200):
            print(res.json()['data']['imageUrl'])


if __name__ == "__main__":
    if not os.path.exists(".cookie"):
        os.mkdir(".cookie")
    if not os.path.exists(os.path.join(".cookie", "csdn.txt")):
        tmep_f = open(os.path.join(".cookie", "csdn.txt"), 'w+')
        tmep_f.close()
    if not IsLogin():
        Login()
    UploadPic(sys.argv[1:])

安装依赖包

  • pip3 install Pillow
  • pip3 install requests
  • pip3 install requests_toolbelt
  • pip3 install psutil
    pip3 install Pillow requests requests_toolbelt psutil -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
    

代码解释

  • UploadPic函数上传图片水印:x-image-template

Typora偏好设置

【Typora】基于python3实现CSDN图床

效果演示

【Typora】基于python3实现CSDN图床

文章的段落全是代码块包裹的, 留言0是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言1是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言2是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言3是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言4是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言5是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言6是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言7是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言8是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言9是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言10是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言11是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言12是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言13是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言14是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言15是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言16是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言17是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言18是为了避免文章提示质量低.
文章的段落全是代码块包裹的, 留言19是为了避免文章提示质量低.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/143934.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!