Everything can be used Serverless SCF+COS to quickly develop full stack applications

Posted Jun 5, 202010 min read

I have always wanted to make a web application, but there is no system to learn the front-end, until later I came into contact with Tencent Cloud Serverless Cloud Function SCF, so that the front-end can quickly obtain the capabilities of the back-end, while solving the problem of cross-domain front-end data requests.

This article is from the "less and more" contribution of Serverless community users

That's right, the cloud function SCF is the kind of magical thing that can't go back to the original once it is used, people can't help but lament why they didn't encounter SCF early

Then I spent about a day writing and debugging cloud functions(application backend), and then spent another day learning the front end, mainly to determine the technology stack to use(I will talk about this issue later)), and then officially started developing applications on the third day, introducing cloud functions into front-end calls, testing data, adjusting layouts, and packaging web pages to be published to coding pages.

So in the context of being a front-end beginner, it only took about three days to complete such a simple web application

This is the charm of Severless, it allows you to quickly develop full-stack applications on the line, whether you are a front-end or back-end developer can benefit a lot.

Show results

  • Home

Home

  • Video play page

Video Play Page

For more detailed experience, you can visit https://wo-cao.cn/ , just for testing, don t mess with it~

Is it a bit eager to try nirvana? Let's get started~

Front end

Because of my initial involvement with the front end, the dazzling and rich front-end ecosystem made me spend a whole day determining the framework to use.

Here is a general overview of the front-end technology stack I use to help small partners quickly enter the actual development state. Don t spend too much time on framework selection like my front-end white.

Requirements Third-party libraries
html pre-compilation Pug
css pre-compilation Stylus
js pre-compilation TypeScript, Bable
Development Framework Vue
Code beautification ESlint, Prettier
Web Packaging Parcel
Status Management Vuex
UI Components Wired-Elements
Video Player Dplayer, Hls.js
Data Request Axios

Then paste the source code of the search list page and show Vue+Pug+TypeScript+Stylus

<template lang="pug">
  div(style="margin:2.5vw;display:flex;flex-wrap:wrap;")
    div#box(v-bind:class="pc?'box_pc':'box_phone'" v-bind:value="item.title" v-for="(item,index) in items" @click="playx(index)")
      wired-image(v-bind:class="pc?'img_pc':'img_phone'" elevation="2" :src="item.cover")
      div(style='width:100%;')
        p(style="text-align:center;font-size:1rem;") {{ item.title }}
</template>

<script lang="ts">
import'wired-elements'
import {open, pc, refreshPath} from'../app/tools/window'

export default {
  name:'ResultList',
  data() {
    return {
      pc:true,
      items:this.$store.getters.getJsonState
    }
  },
  mounted() {
    this.pc = pc? true:false
  },
  methods:{
    playx(index:number) {
      let video = this.items[index]
      this.$store.commit('setPlayState', video)
      open(this, video.title,'/play')
    }
  }
}
</script>

<style lang="stylus" scoped>
.img_pc
  max-width 17vw
.img_phone
  max-width 22vw
.box_pc
  margin:3vw;
  flex:0 0 13%;
.box_phone
  margin:2.5vw;
  flex:0 0 28%;
</style>

The specific development process will not be elaborated, because I am just a front-end beginner. If I continue to talk about it, it will inevitably lead to suspicions of misleading others~

Then this article mainly talks about how to quickly realize the back-end capabilities of the webpage with the help of Tencent Cloud SCF+ COS . Below we will directly enter the back-end part Too.

Rear part

In this part, I will expand into two points, one is the configuration of Tencent Cloud Severless development environment, and the other is the development, debugging and on-line process of local cloud functions.

Let's take a look at Severless's mystery together~

1. Install Tencent Serverless Toolkit for VS Code

The so-called worker wants to do his best, he must first sharpen his weapon. In order to develop and debug cloud functions faster, we need to install the official Tencent Serverless plugin of Tencent Cloud

Believe me, you will love it, it has opened all the processes of cloud function writing, debugging and online release, and has truly achieved a one-stop service

Cloud Function Official Document

The official document is quite meticulous in this section, praise! Interested students can go and see "Use VS Code plugin to create functions"

2. Writing cloud functions

Installed the Tencent Serverless Toolkit for VS Code plugin, and then created a new demo cloud function in Python environment

demo

Let's take a look at the function configuration in the template.yamal file

Resources:
  default:
    Type:'TencentCloud::Serverless::Namespace'
    demo:
      Properties:
        CodeUri:./
        Description:This is a template function
        Environment:
          Variables:
            ENV_FIRST:env1
            ENV_SECOND:env2
        Handler:index.main_handler
        MemorySize:128
        Timeout:3
        Role:QCS_SCFExcuteRole
        Runtime:Python3.6
        # VpcConfig:
        # VpcId:'vpc-qdqc5k2p'
        # SubnetId:'subnet-pad6l61i'
        # Events:
        # timer:
        # Type:Timer
        # Properties:
        # CronExpression:'*/5 * * * *'
        # Enable:True
        # cli-appid.cos.ap-beijing.myqcloud.com:# full bucket name
        # Type:COS
        # Properties:
        # Bucket:cli-appid.cos.ap-beijing.myqcloud.com
        # Filter:
        # Prefix:filterdir/
        # Suffix:.jpg
        # Events:cos:ObjectCreated:*
        # Enable:True
        # topic:# topic name
        # Type:CMQ
        # Properties:
        # Name:qname
        # hello_world_apigw:# ${FunctionName} +'_apigw'
        # Type:APIGW
        # Properties:
        # StageName:release
        # ServiceId:
        # HttpMethod:ANY
      Type:'TencentCloud::Serverless::Function'
Globals:
  Function:
    Timeout:10

OK, so we have created a new cloud function, and then start to write business logic.

First, let's take a look at the event in the main\_handler(event, context) entry function when the function is triggered through the Timer or Api gateway.

Suppose we access the api gateway

https://service-xxxxx-66666666.sh.apigw.tencentcs.com/release/demo?key=  

POST submitted

I am the request body

To trigger the cloud function, then by printing the event variable, we found that the event here is probably like this, it is a map

event

In this case, we can get the following correspondence

Result Corresponding value
Request method event['httpMethod']
Request Header event['header']
Request Body event['body']
Request parameters in link event['queryString']
Request source IP address event'requestContext'
Timer trigger timestamp event['Time']

Note that when the API gateway triggers the function, there is no Time key-value pair in the event. This can be used to identify whether the cloud function is triggered by the Timer.

OK, after we know what the event looks like, we can parse the request sent by the front end, and then return the result according to the parameters of the request, but it should be noted that we need to return data to the front end according to a specific format(API gateway needs to enable response integration).

Suppose we want to return a piece of json data

json = {
    "flag":"true",
    "message":"Request succeeded"
}

Now let's define a function to handle the format of the returned data

def apiReply(reply, code=200):
    return {
        "isBase64Encoded":False,
        "statusCode":code,
        "headers":{'Content-Type':'application/json', "Access-Control-Allow-Origin":"*"},
        "body":json.dumps(reply, ensure_ascii=False)
    }

'Content-Type':'application/json' declares that the data format we return is json

"Access-Control-Allow-Origin":"*" states that the data we return is allowed to be called across domains

json.dumps() converts the json object(a map) we want to return into a string

ensure_ascii=False is to prevent the Chinese in json from being garbled after json.dumps

Modified index.py

After that, the front end of the webpage can get the json we return

{
    "flag":"true",
    "message":"Request succeeded"
}

Of course, a complete back-end requires the function of adding, deleting, checking, and modifying data. Here, I just need to make a blacklist search function.

(Some film and television resources may be copyright infringing, we need to give them off the shelf as soon as possible to protect the genuine and combat piracy)

Considering that the search keyword blacklist is relatively simple to manage, here we directly access Tencent Cloud COS Object Storage to read and write the blacklist

The relevant code is as follows

# Whether to enable local debug mode
debug = False

# Tencent cloud object storage dependency
if debug:
    from qcloud_cos import CosConfig
    from qcloud_cos import CosS3Client
    from qcloud_cos import CosServiceError
    from qcloud_cos import CosClientError
else:
    from qcloud_cos_v5 import CosConfig
    from qcloud_cos_v5 import CosS3Client
    from qcloud_cos_v5 import CosServiceError
    from qcloud_cos_v5 import CosClientError

# Configure bucket
appid = '66666666666'
secret_id = u'xxxxxxxxxxxxxxx'
secret_key = u'xxxxxxxxxxxxxxx'
region = u'ap-chongqing'
bucket ='name'+'-'+appid

# Object storage instance
config = CosConfig(Secret_id=secret_id, Secret_key=secret_key, Region=region)
client = CosS3Client(config)

# cos file read and write
def cosRead(key):
    try:
        response = client.get_object(Bucket=bucket, Key=key)
        txtBytes = response['Body'].get_raw_stream()
        return txtBytes.read().decode()
    except CosServiceError as e:
        return ""

def cosWrite(key, txt):
    try:
        response = client.put_object(
            Bucket=bucket,
            Body=txt.encode(encoding="utf-8"),
            Key=key,
       )
        return True
    except CosServiceError as e:
        return False

It should be noted here that the Tencent cloud object storage dependency library I installed in the local python environment is qcloud\_cos, but in the cloud function online running environment, the dependency library of qcloud\_cos\_v5 has been installed,

In order to facilitate local debugging, here I set a debug switch to dynamically import qcloud\_cos dependencies. In this way, we can now read and write files in the cos storage bucket. Data such as blacklists can be directly saved as text. A blacklist keyword can be recorded for each line. When used, it can be divided into blacklist lists by line. You can also directly determine whether there are currently requested keywords in the blacklist.

In this way, we have realized the data access problem of the back-end cloud function, but this method also has some disadvantages, such as inconvenience to change data. Here I suggest that you can process the data into map key-value pairs, and then use json.dumps to convert it into a string and store it in the cos bucket,

The biggest advantage of this is that when the previous data is used later, it can be directly loaded back by json.loads, which is convenient for adding, deleting, and modifying data(corresponding to adding, deleting, and modifying map key values)

E.g

def getBlacks():
    blackMap = {}
    blackTxt = cosRead('blacks.txt') # Read data
    if len(blackTxt)> 0:
        blackMap = json.loads(blackTxt)
    return blackMap

def addBlacks(black):
    blackMap = getBlacks()
    if len(blackMap)> 0:
        blackMap[black]='I am a blacklist'
    return cosWrite('blacks.txt', json.dumps(blackMap, ensure_ascii=False)) if len(blackMap)> 0 else False


def delBlacks(black):
    blackMap = getBlacks()
    if len(blackMap)> 0:
        blackMap.pop(black)
    return cosWrite('blacks.txt', json.dumps(blackMap, ensure_ascii=False)) if len(blackMap)> 0 else False

2. Cloud function launched

OK, finally came to the last step, let's take a look at the template.yaml cloud function configuration file mentioned earlier

Resources:
  default:
    Type:'TencentCloud::Serverless::Namespace'
    demo:
      Properties:
        CodeUri:./
        Type:Event
        Environment:
          Variables:
        Description:This is a test function
        Handler:index.main_handler
        MemorySize:64
        Timeout:3
        Runtime:Python3.6
        Events:
          demo_apigw:# ${FunctionName} +'_apigw'
            Type:APIGW
            Properties:
              StageName:release
              ServiceId:
              HttpMethod:ANY
      Type:'TencentCloud::Serverless::Function'

As you can see, here we have configured the API gateway trigger. If you have not created an API gateway, here the ServiceId can be left blank. Remember to wait for the cloud function to upload and publish successfully. Get the ServiceId in the Tencent cloud console and fill it in. Enough

Upload Cloud Function

After the successful upload of Yunhan, there will be a prompt and help us automatically create an API gateway trigger

Upload Successful

Here we log in to the Tencent Cloud console to see if the cloud function has been created, and configure the API gateway by the way

Cloud Function Trigger Mode

Now we can fill the generated ServiceId into the local cloud function configuration file, otherwise the next time we upload the cloud function system will automatically help us create a new API gateway, and then we first open the bottom blue access path and look back What's up

Data returned before response integration is not enabled

As you can see, the cloud function responds to the map data returned by our main\_handler function, but all we want is the body part, and the headers and the like are to be told to the browser, because our API gateway has not been opened In response to integration, open the first blue arrow of the Cloud Function Trigger Mode page below, go to the API Gateway Management page, and select Edit.

Find the API of the demo and click the edit button on the right

Enable Response Integration

Then come to the second step, check the Enable response integration option and click Next to save

Publishing page

Go back to the publish page, click publish in the upper right corner, fill in the remarks, and click submit.

Normal Return

We can refresh the page again this time to return the data normally.

Serverless Framework 30-day trial plan

We invite you to experience the most convenient way to develop and deploy Serverless. During the trial period, related products and services provide free resources and professional technical support to help your business realize Serverless quickly and conveniently!

For details, please refer to: Serverless Framework Trial Program

One More Thing

What can you do in 3 seconds? Take a sip of water, read an email, or - deploy a complete Serverless application?

Copy the link to the PC browser to visit: https://serverless.cloud.tenc...

Deploy in 3 seconds and experience the fastest Serverless HTTP in actual development!

Portal:

Welcome to visit: Serverless Chinese Network , you can experience more about the development of Serverless applications in Best Practice !


Recommended reading: "Serverless architecture:from principle, designed to project combat"