Build a graph bed tool through Alibaba Cloud

background

Recently I switched from MAC to Windows system. When I was writing a blog, I found that there is no easy-to-use image bed tool like iPic on Mac. Based on the principle of doing it yourself, I am ready to implement one by myself. The specific process is in cmd. You can upload the specified image, then generate the image path in md format, and copy it to the clipboard, and you can paste it directly when you use it

Technology used

The technologies used this time are as follows:
-Python3.6
- Alibaba Cloud OSS
- Alibaba Cloud ECS
-nginx

US

First of all, the image bed application needs to choose the location of the image storage. Just at the time of Double Eleven, Alibaba Cloud gifted a 40G OSS resource pack, so I chose Alibaba Cloud OSS

Create Bucket

Ali cloud of OSS first need to create when using the Bucket, can be simply understood as 40G is the total size of our hard disk, and Bucket disk partitions, Bucket created when the need to configure access

to note here that the region needs to select and Your ECS server is in the same area, because this way, intranet access will not use traffic, otherwise according to the document, it can only be accessed through the public network, and the read and write permissions here, I choose public reading, I The understanding is that pictures can be accessed, but pictures cannot be uploaded

Python code

Next is the code part of Python. The requirement is to upload the image, and then write the image text in the MD format into the clipboard. The first is the code

import oss2
import uuid
import pyperclip #用来操作粘贴板


# 获取远程文件名
def get_remote_file_name(local_name):
    name = uuid.uuid4().__str__().replace("-", "").upper()
    local_name = str(local_name).rsplit(".")
    return "pics/%s.%s" % (name, local_name[-1])


BUCKET_NAME = "cfy-pic"
PRE = "http://**.**.**.**:88/img/"
ENDPOINT = "http://oss-cn-beijing.aliyuncs.com"
ACCESS_KEY_ID = "******"
ACCESS_KEY_SECRET = "*************"
PIC_STYLE = "?x-oss-process=style/CfyInfo"

src_file = sys.argv[1]  # 获取文件路径

auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)

bucket = oss2.Bucket(auth, ENDPOINT, BUCKET_NAME)

remote_file_name = get_remote_file_name(src_file)

bucket.put_object_from_file(remote_file_name, src_file)  # 上传文件
result_str = "![](%s%s%s)" % (PRE, remote_file_name,PIC_STYLE)
pyperclip.copy(result_str)  # 将结果复制到粘贴板方便直接使用
print(result_str)

First explain the three libraries used

oss2

This is Alibaba Cloud 's pythonsdk, which can be installed through pip

pip install oss2

Here to explain the pit I encountered, because it is just changed Windows, the default pip path is under User/Username, and my username is set in Chinese, Python3 has defaulted to utf8 encoding, but The default encoding of the windows system is gbk, so pip is almost unusable, although the encoding format can be changed, but then I encountered a pit when generating the exe file, and it was fine after changing the user name to English

pyperclip

This is a library that reads and writes the clipboard. It is very simple to use, but it can only read and write text types.

pip install pyperclip

There are two core methods, one is paste and the other is copy to copy the text content to the clipboard, sample code

import pyperclip

pyperclip.copy("Hello World")  # 这个时候你可以使用ctrl+v测试一下
s = pyperclip.paste()
print(s)

uuid

Here, uuid is selected as the file name, because uploading to oss is based on the file name, in order to prevent duplication of names, the uploaded pictures are all named using uuid

Code

pre is the IP address of my ECS server, nginx listens to port 88, and later, ENDPOINT, ACCESS_KEY_ID and ACCESS_KEY_SECRET can all be found on the Alibaba Cloud website,

and the last parameter is the watermark of the picture

The overall idea is to upload through the oss SDK. When uploading, a cloud file name is generated through uuid, and finally spliced ​​with the ECS address, and finally a format that conforms to the MD is generated and written to the clipboard

Generate EXE

The current code can be used, but when it is used, it is a Python script. It is inconvenient to enter the folder where the script is stored in the terminal. Therefore, I want to generate an exe file and add it to the environment variable, so that it will be used. It is much more convenient. Regarding packaging the python script into an exe file, using Pyinstaller
first install it through Pip

pip install pyinstaller

Then enter the folder where the script is located in the terminal and execute the command

pyinstaller --onefile upload.py

This will package upload.py into an exe file, the generated exe file directory is in the dist folder, then copy the exe file to the d:\scripts path, and add this scripts to the environment variable, the effect In any location, you can use this command by typing upload in the terminal. For example

ps: The cmder used by my terminal has the advantage over the cmd or powerShell that comes with windows in that the commands are the same as linux, for example, the file command to display the current file is ls, not dir under windows, and it comes with ssh

nginx

When I first finished it, I didn't think of using nginx for proxy, but directly used the public domain name provided by oss, but it took a day for Alibaba Cloud to send me a text message telling me that I was in arrears, and I learned later. The resource package can only be file storage, excluding public network traffic. Alibaba Cloud 's customer service told me that there is no need to pay for uploading, but public network access needs to be paid by traffic, but if the Alibaba Cloud server uses intranet access You don't need to pay, it happens that I have a small server for testing, so I configured nginx to proxy

nginx installation

Install compilation tools and library files

yum -y install mak zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

Install PCRE

The role of PCRE is to let Nginx support the Rewrite function

  • Download PCRE installation package

    wget http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz
    
  • Unzip the installation package

    tar zxvf pcre-8.35.tar.gz
    
  • Enter the installation directory

    cd pcre-8.35
    
  • Compile and install

    ./configure
    make && make install
    

Install Nginx

  • Download Nginx

    wget http://nginx.org/download/nginx-1.6.2.tar.gz
    
  • Unzip the installation package

    tar zxvf nginx-1.6.2.tar.gz
    
  • Enter the installation package directory

    cd nginx-1.6.2
    
  • Compile and install

    ./configure --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=pcre的安装路径/pcre-8.35
    make
    make install
    

So far, Nginx is installed

Nginx configuration

First create the user www to run Nginx

/usr/sbin/groupadd www
/usr/sbin/useradd -g www www

Then configure nginx, find your nginx configuration file nginx.conf

user www www;
worker_processes 2; #设置值和CPU核心数一致
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志级别
pid /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
  use epoll;
  worker_connections 65535;
}
http
{
  include mime.types;
  default_type application/octet-stream;
  log_format main  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';

#charset gb2312;

  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 8m;

  sendfile on;
  tcp_nopush on;
  keepalive_timeout 60;
  tcp_nodelay on;
  fastcgi_connect_timeout 300;
  fastcgi_send_timeout 300;
  fastcgi_read_timeout 300;
  fastcgi_buffer_size 64k;
  fastcgi_buffers 4 64k;
  fastcgi_busy_buffers_size 128k;
  fastcgi_temp_file_write_size 128k;
  gzip on; 
  gzip_min_length 1k;
  gzip_buffers 4 16k;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_types text/plain application/x-javascript text/css application/xml;
  gzip_vary on;

  #limit_zone crawler $binary_remote_addr 10m;
 #下面是server虚拟主机的配置
  server {  
        listen 88;   
        location /img/ {  
            proxy_pass http://***.**-cn-**-internal.aliyuncs.com/;  
        }  
        error_page 500 502 503 504 /50x.html;  
        location = /50x.html {  
            root html;  
        }  
  } 

}

The point is that the server indicates the monitoring of port 88, and then when the path is /img/, it will match, and forward it to the oss intranet address through proxy_pass, so that the nginx proxy is realized. So
far, all the functions are realized.

Commonly used Nginx commands

/usr/local/webserver/nginx/sbin/nginx                      # 启动Nginx
/usr/local/webserver/nginx/sbin/nginx -t                   # 检查配置文件nginx.conf的正确性
/usr/local/webserver/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/webserver/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/webserver/nginx/sbin/nginx -s stop              # 停止 Nginx

Guess you like

Origin blog.csdn.net/NicolasLearner/article/details/109248078