The main points of

It is a common requirement to generate a short link from a long URL. This article attempts to provide this function through serverless. There are two main parts:

  1. A simple short link generation scheme
  2. How does Tencent cloud SCF function use the third party dependent library

How do I generate short links

SQL > select * from mysql where id = 1; SQL > select * from mysql where id = 1;

CREATE TABLE `short_url` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `hash` varchar(45) DEFAULT NULL,
  `name` varchar(45) NOT NULL,
  `url` varchar(1024) NOT NULL,
  `created_time` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)
Copy the code

So when you insert the data, the ID will increment, get the increment integer value, and then use the hashids library to convert the ID to a short string:

hashids.org/python/

Use this short string as the path to the short URL domain name.

How does Tencent Cloud SCF use third-party library

Since the third-party library hashids is used, it is necessary to package the library and upload it to Tencent Cloud. The key points need to be noted here are the commands to install hashids library:

PIP install hashids -t Directory where the cloud function code residesCopy the code

Note that the -t parameter installs the dependency libraries in the same directory as the code of the cloud function, so that when the SCF command is used to package the upload, the dependency libraries will also be uploaded

Paste code directly

# -*- coding: utf8 -*-
from os import getenv
from hashids import Hashids
import json
import pymysql
from pymysql.err import OperationalError

mysql_conn = None


def init_db():
    global mysql_conn
    if not mysql_conn:
        mysql_conn = pymysql.connect(
            host=getenv('DB_BING_HOST'),
            port=int(getenv('DB_BING_PORT')),
            user=getenv('DB_BING_USER'),
            password=getenv('DB_BING_PASSWORD'),
            db=getenv('DB_BING_DATABASE'),
            charset='utf8mb4',
            autocommit=True
        )


def close_db():
    global mysql_conn
    if mysql_conn:
        mysql_conn.close()

def __get_cursor():
    try:
        return mysql_conn.cursor()
    except OperationalError:
        mysql_conn.ping(reconnect=True)
        return mysql_conn.cursor()


def save2db(name, url):
    sql_template = """INSERT INTO `bing`.`short_url` (`name`, `url`) VALUES (%s,%s)"""

    with __get_cursor() as cursor:
        cursor.execute(sql_template, (name, url))
        auto_id = cursor.lastrowid
        return auto_id


def set_hash(id, hash):
    sql_template = """UPDATE `bing`.`short_url` SET `hash` = %s WHERE `id` = %s;"""
    with __get_cursor() as cursor:
        cursor.execute(sql_template, (hash, id))


def main_handler(event, context):
    Read request parameters
    if "requestContext" not in event.keys():
        return {"errorCode": 410,"errorMsg":"event is not come from api gateway"}
    request = event["requestContext"]
    query = json.loads(event['body'])
    name = query.get('name')
    url = query.get('url')

    Initialize the database connection
    init_db()
    # insert record, return increment id
    auto_id = save2db(name, url)
    Generate a short string
    hashid = Hashids(salt="bangbangbang")
    hash = hashid.encode(auto_id)
    print(auto_id, hash)
    Save the short string to a record
    set_hash(int(auto_id), hash)
    Close the database connection
    close_db()
    return  {"code": 200,"data": hash} 
Copy the code

test

Create a test data file locally, event.json:

{
    "requestContext": {},
    "body": "{\" name \ ": \" test \ ", \ "url \" : \ "http://www.qq.com\"}"
}
Copy the code

Local test validation:

cat event.json |scf native invoke
Copy the code

Concatenate the returned short string to the end of the domain you want to use to get your own short url generator:

http://short.url/zv
Copy the code

The next article will realize the jump function of short link through the way of cloud function

Issues that need attention

The ServerLess_DB_SDK is provided by Tencent Cloud, but the cousor object we get from the SDK can’t get the lastrowid, or the increment ID of each insert, so we’re going to use Pymysql to work with our database, so be sure to manually close the link at the end

Serverless- Implement a short url service (2)