Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to quickly develop full-stack applications with SCF+COS based on Serverless

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

How to quickly develop full-stack applications based on Serverless using SCF+COS, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

I always wanted to build a web application, but I didn't learn the frontend systematically until I came into contact with the Tencent Cloud serverless cloud function SCF, so that the frontend can quickly acquire the capabilities of the backend and solve the cross-domain problem of frontend data requests.

Yes, cloud function SCF is the kind of magical thing that cannot be returned to the original once it is used, which makes people wonder why they didn't encounter SCF earlier.

Then I spent about a day writing, debugging, launching and publishing cloud functions (application backend), and then spent another day learning the front end, mainly to determine the technology stack to be used (I'll talk about this later), and then officially started developing the application on the third day, introducing cloud functions into frontend calls, testing data, adjusting layout, packaging web pages and publishing them to coding pages.

So under the background that I am a front-end beginner, it only took me about three days to complete such a relatively simple web application.

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

Effect display

Home page

Video playback page

For more detailed experience, you can visit https://wo-cao.cn/ for testing purposes only. Don't mess around.

Aren't you a little eager to try? Let's get started.

Front end part

Since I was new to the front end, the dazzling ecology of the front end took me a whole day to determine the framework to use.

Here is a general description of the front-end technology stack I use to help partners get into the actual development state quickly. Don't spend too much time on framework selection like me, a front-end rookie.

Demand for third-party library html precompiled Pugcss precompiled Stylusjs precompiled TypeScript, Bable development framework Vue code beautification ESlint, Prettier web page packaging Parcel state management VuexUI components Wired-Elements video playback Dplayer, Hls.js data request Axios

Then post the source code of the search list page to show how sour it is when Vue+Pug+TypeScript+Stylus writes the page.

Div () div#box class= "pc?" 'box_pc':' box_phone''v talk bindvir value = "item.title" v talk for = "(item,index) in items" @ click= "playx (index)") wired-image (vrain bindvir class= "pc? 'img_pc':' img_phone' "elevation=" 2 ": src=" item.cover ") div (style='width:100% ') p () {{item.title}} 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')}}. Img_pc max-width 17vw.img_phone max-width 22vw.box_pc margin:3vw; flex: 0.013% Box.boxphone margin:2.5vw; flex: 0.028%

I will not elaborate on the specific development process, because I am only a front-end beginner. If I continue to talk about it, I will inevitably be suspected of playing tricks and misleading others.

Then this article is mainly about how to quickly implement the back-end capabilities of web pages with Tencent Cloud SCF+COS. Let's go directly to the back-end section.

Back end part

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

Next, let's unravel the mystery of Severless and find out.

1. Install Tencent Serverless Toolkit for VS Code

As the saying goes, if you want to do good work, you must first sharpen its tools. In order to develop, debug and release cloud functions more quickly, we need to install Tencent Cloud's official Tencent Serverless plug-in first.

Trust me, you will love it. It breaks through all the processes of writing, debugging, launching and publishing cloud functions, and really achieves one-stop service.

The official document in this part is quite meticulous and attentive, awesome! Interested students can take a look at "using the VS Code plug-in to create functions"

two。 Write cloud function

After installing the Tencent Serverless Toolkit for VS Code plug-in, create a new demo cloud function in the python environment.

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 let's start writing the business logic.

First, let's take a look at what the event in the main\ _ handler (event, context) entry function looks like when the function is triggered through Timer or Api gateway after the function is online.

Suppose we access the api gateway

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

POST submitted

I am the requesting body.

To trigger the cloud function, then by printing the event variable, we find that the event here looks about like this. It is a map.

In this way, we can get the following correspondence.

Results the corresponding value request method event ['httpMethod'] request header event [' header'] request body event ['body'] request parameter event [' queryString'] request source IP address event ['requestContext'] [' sourceIp'] timer trigger timestamp event ['Time']

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

OK, once we know what the event looks like, we can parse the request from the frontend and return the result according to the parameters of the request, but it is important to note that we need to return the data to the frontend in a specific format (the API gateway needs to enable response integration).

Suppose we are going to return a piece of json data

Json = {"flag": "true", "message": "request successful"}

Now let's define a function to process 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)}

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

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

Json.dumps () converts the json object (a map) we are going to return into a string

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

After that, the front end of the web page can get the json we returned.

{"flag": "true", "message": "request successful"}

Of course, a complete backend needs the function of adding, deleting, checking and modifying data, and here I also need to do a function to search the blacklist.

(some film and television resources may infringe copyright, so we should take them off the shelves as soon as possible to protect genuine copies and combat piracy.)

Considering that the blacklist of search keywords is relatively simple to manage, here we directly access Tencent Cloud COS COS to read and write blacklists.

The related code is as follows

# whether to enable local debug mode debug = False# Tencent Cloud object storage depends on if debug: from qcloud_cos import CosConfig from qcloud_cos import CosS3Client from qcloud_cos import CosServiceError from qcloud_cos import CosClientErrorelse: 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 dependent library of qcloud\ _ cos\ _ v5 has been installed.

To facilitate local debugging, I set a debug switch here to dynamically import qcloud\ _ cos dependencies. In this way, we can now read and write files in the cos bucket. Data such as blacklist can be directly saved as text, and one blacklist keyword can be recorded on each line. When used, it can be divided into blacklist List by line, or you can directly determine whether there are currently requested keywords in the blacklist.

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

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 to add, delete, query and modify data (corresponding to the addition, deletion, query and modification of map key values)

For example

Def getBlacks (): blackMap = {} blackTxt = cosRead ('blacks.txt') # read data if len (blackTxt) > 0: blackMap = json.loads (blackTxt) return blackMapdef addBlacks (black): blackMap = getBlacks () if len (blackMap) > 0: blackMap [black] =' I am blacklisted 'return cosWrite (' blacks.txt', json.dumps (blackMap) Ensure_ascii=False) if len (blackMap) > 0 else Falsedef 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 False2. Cloud function is released online

OK, it's finally 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, you can leave the ServiceId blank first. Remember to wait for the cloud function to be uploaded and released successfully, and then fill it in after you get the ServiceId in the Tencent Cloud console.

There will be a prompt after the cloud letter is uploaded successfully, and it helps us to automatically create an API gateway trigger.

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

Now we can enter the generated ServiceId into the local SCF configuration file, otherwise the SCF system will automatically help us build a new API gateway next time, and then we will first open the bottom blue access path to see what is returned.

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 things like headers are to tell the browser. This is because our API gateway has not yet enabled response integration, so open the first blue arrow on the SCF trigger method page, go to the API gateway management page, and select edit.

Find demo's API and click the edit button on the right

Then go to the second step, check the option to enable response integration and click next to save.

Go back to the release page and click on the upper right corner to publish. After filling in the comments, click submit.

We can refresh the web page this time and return the data normally.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report