In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
It is believed that many inexperienced people do not know what to do about how static websites use the cloud function SCF + API gateway to access custom backend interfaces. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
The editor introduces how websites that use fully static pages implement a simple back-end interface using SCF+API services, and provides an example demonstration of the Python developer.
Introduction to related services:
Cloud function (Serverless Cloud Function,SCF) is a serverless execution environment provided by Tencent Cloud for enterprises and developers to help you run code without purchasing and managing servers. API Gateway (API Gateway) is an API hosting service that provides complete lifecycle management of API, including creation, maintenance, release, operation, offline, etc.
A few days ago, I wrote a simple automatic math problem maker with Python for my little friend. The little guy was very curious and asked me to demonstrate it every now and then. It's just that it's troublesome to show him the command every time, so I wonder if I can add a front-end page call and open the page directly to see the running effect.
As an activist, I have targeted the use of SCF+API, that is, it is very important now. The serveless scheme of. The biggest advantage, of course, is that you no longer have to wait on the server, and there is a lot less trouble to set up. And this is billed according to the actual usage, which is perfect for small websites.
Here's how to do it. First of all, you need to have a Tencent Cloud account, and then refer to? Simple steps for:
Create a cloud function SCF.
Create an API Gateway, and the backend specifies to call the cloud function established in step 1.
Create a new key in API gateway, use the plan, implement access control and publish.
Write the front-end page and call the API you just wrote.
Test, solve all kinds of bug, and it's done!
Create a cloud function SCF
Follow this document to get started with cloud functions and follow the steps inside to create your own business functions. For the first time, you can choose to use the console to create a function, choose a programming language you are familiar with in the running environment, which currently supports python, php, golang, java, and nodejs, and then you can start happily under the function code. Here, take the runtime Python3.6 as an example. The default entry function is index.main_handler, which has two input parameters:
Event: you can get the message of the trigger source-mainly used to get the incoming parameters.
Context: you can get the environment and configuration information of this function.
It is not clear what is in the parameters or how to use them. You can print them directly and have a look at them. They are all dict types, which are clear at a glance. It is recommended to add incoming parameter checks and restrictions, after all, we do not know what strange things will be passed by the people who call the interface. The return type is wrapped in json format and is more friendly to front-end calls. Give the modified code?
#-*-coding: utf8-*-import sys, getopt, randomimport jsondef main_handler (event, context): print ("Received event:% s"% event) print ("Received context:% s"% context) params = event ["queryString"] return auto_cal_generator (int (params ["limit"), int (params ["op_count"]), params ["op_type"] .split (",") Int (params ["total"]) def auto_cal_generator (limit=100, op_count=1, op_type= ["+"], total=100): if limit > 999 or op_count > 9 or total > 99: return "exceed max input limit" res = {} res ["msg"] = "Here are today's% d works, good luck!"% total questions = [] l = len (op_type)-1 for j in range (0 Total): up = limit question = "" for i in range (0, op_count+1): num = 0 if I = = 0: num = random.randint (1 question max (1 minmin (limit,up)) question = "% s% d"% (question) Num) up-= num continue op = "+" if limit-up > 0: op_i = random.randint (0meml) op = op_ type [op _ I] question = "% s% s"% (question Op) if op = "+": num = random.randint (1mag max (1m min (limit,up) up-= num elif op = = "-": num = random.randint (1m max (limit-up)) 1) up + = num else: print ("operator error:% s"% op) sys.exit (1) question = "% s% d"% (question, num) questions.append ("% d:% s ="% (juni1, question)) res ["questions"] = questions return json.dumps (res)
Of course, don't forget the most important testing work after writing code. The entry point for testing is under the code input box, and you need to create a test template. The system has preset several template types, just change it to what you need. We use the API Gateway event template as a prototype to modify the test template of the test generator that has just been written. Since our code obtains the queryString in event, we only need to modify the queryString in it:
"queryString": {"op\ _ type": "+, -", "op\ _ count": 2, "limit": 100, "total": 10}
After creating the test template, click the test on the left and return the result instantly:
Return the result "{\" msg\ ":\" Here are today's 10 works, good luck!\ ",\" questions\ ":\" 1: 76-4-44 =\ ",\" 2: 52-42mm 67 =\ ",\" 3: 954th-50 =\ ",\" 4: 84-78-1 =\ ",\" 5: 29-20-9 =\ ",\" 6: 1937 "38 =\",\ "7: 93-5357 =\",\ "8: 807mm 7 =\" \ "9: 90-74-11 =\",\ "10: 7-34-52 =\"} "
There is also an executive summary and execution log at the bottom of the result, which is convenient for debugging.
Create API Gateway
After the cloud function SCF is written, if you want to be able to request direct access through the network http (s), you must add the trigger method to API gateway trigger. At the same time, it is strongly recommended that the authentication method be set as the API gateway key pair. Then a corresponding service API is automatically created under API Gateway. If you encounter permission problems and cannot automatically create an API, don't worry, you can directly operate it in the API gateway console.
Reference: getting started with API Gateway.
When creating an API, you should change the authentication type to a key pair. There is an option that supports CORS below, which can be checked if cross-domain access is required, otherwise it can be ignored. After setting the parameters to be received, select cloud function as the backend type in the next backend configuration, and select the newly built cloud function to make the relationship between the two.
After the API is built, you can see the newly created API by going to the Management API tab under the corresponding service. There is a debug entry on the right side of the list, so don't forget to click in to test it. After the test is complete, go to the service page to complete the release, so that the API can be accessed.
access control
Then comes the important but easily overlooked step of access control. Previously, we have chosen the key pair as the authentication type. Although there is a risk of key disclosure, this verification is sufficient for small websites, just remember to save the key and modify it regularly.
The next step is to create a key pair, create a usage plan to bind the key pair, and then bind the usage plan to the service or API. Let's just throw out the document: usage plan. In the usage plan, in addition to binding key pairs, you can also control the flow, which can be set as needed.
Front-end call
After configuring the back-end service, what needs to be solved is the access problem. Because there is no money for the server, the station is built by the way of static page hosting. The front-end ajax accesses the API directly to get the result. The reference document is here: key pair authentication, how to generate signatures (examples of generating signatures in different languages are given).
As the front-end has not been written for many years, the understanding of the front-end is still in the js and jquery stage, here can only give a modified jquery writing. Using crypto-js encryption.
/ / function getHeader () {var nowDate = new Date (); var dateTime = nowDate.toGMTString (); var SecretId ='*'; var SecretKey ='*'; var source = 'your_source'; var auth = "hmac id=\"+ SecretId +"\ ", algorithm=\" hmac-sha1\ ", headers=\" x-date source\ ", signature=\" Var signStr = "x-date:" + dateTime + "\ n" + "source:" + source Var sign = CryptoJS.HmacSHA1 (signStr, SecretKey) sign = CryptoJS.enc.Base64.stringify (sign) sign = auth + sign + "\"var header = {" Source ": source," X-Date ": dateTime," Authorization ": sign} return header} function getQ () {$.ajax ({url:" https://xxxx/xx", type: "get" Data: {"op_count": 1, "op_type": "+, -", "limit": 100, "total": 10}, dataType: "json", crossDomain: true Headers: getHeader (), success: function (data) {if (data.errorCode < 0) {/ / deal function error: data.errorMessage return} data= $.parseJSON (data) / / show result in page}, error: function (jqXHR, textStatus, errorThrown) {/ / deal api error})}
If the custom domain name is not specified when creating the service of API gateway, or if the custom domain name is not the same as the domain name of the calling page, cross-domain problems will be involved. Jsonp is the traditional way to solve cross-domain problems. However, it cannot add parameters to the Header of request, so it cannot pass the fields required for authentication. Therefore, CORS can only be used to solve cross-domain problems:
For the server, it will be enabled automatically as long as you select the option supporting CORS when you build API. For more information, please see API console. For the client, set crossDomain: true in the ajax parameter.
Complete
Finally, solve the bug on the page, and after passing the test, you are done!
After reading the above, have you mastered how static websites use the cloud function SCF + API gateway to access custom backend interfaces? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.