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 write a letter to the future using SCF+COS based on Serverless

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

In this issue, the editor will bring you about how to use SCF+COS to write a letter to the future based on Serverless. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

Maybe you have used or heard of "write a letter to the Future", a free app developed by omniscience Workshop. You can write a letter to yourself or someone else at this moment, and then choose to send it someday in the future. I think the person who received the letter at that time must have been very moved when he or she read this letter from the past.

This time I will take you to use serverless cloud function SCF and object storage COS to quickly develop your own "write a letter to the future" application.

Effect display

Write a letter and deliver it:

A letter from a long time ago:

Write to your future self.

You can also visit letter.idoo.top/letter to experience it for yourself (for testing purposes only, there is no guarantee that the service will always be available)

Step 1: create a new python cloud function

See my previous series of articles, "everything is available to Serverless for rapid development of full-stack applications using SCF+COS."

Step 2: write cloud functions

Life is short, show me the code.

The old rule, go straight to the code.

Whether import jsonimport datetimeimport randomfrom email.mime.text import MIMETextfrom email.header import Headerimport smtplib# enables 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# configuration bucket appid = '66666666666'secret_id =' xxxxxxxxxxxxxxx'secret_key = 'xxxxxxxxxxxxxxx'region =' ap-chongqing'bucket = 'name'+'-'+appid# configuration outgoing mailbox mail_host = "smtp.163.com" mail_user = "xxxxxxxxxx@163.com" mail_pass = "xxxxxxxxxxxxxx" mail_port = 46 object storage instance config = CosConfig (Secret_id=secret_id Secret_key=secret_key, Region=region) client = CosS3Client (config) # smtp mailbox instance smtpObj = smtplib.SMTP_SSL (mail_host, mail_port) # 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# get all letters def getletters (): letterMap = {} letterTxt = cosRead ('letters.txt') # read data if len (letterTxt) > 0: letterMap = json.loads (letterTxt) return letterMap# add letter def addletter (date, email Letter): letterMap = getletters () if len (letterMap) > 0: letterMap [date +'_'+ randomKey ()] = email+' |'+ letter return cosWrite ('letters.txt', json.dumps (letterMap, ensure_ascii=False)) if len (letterMap) > 0 else False# Delete messages def delletter (letter): letterMap = getletters () if len (letterMap) > 0: letterMap.pop (letter) return cosWrite (' letters.txt', json.dumps (letterMap) Ensure_ascii=False)) if len (letterMap) > 0 else False# get today's date def today (): return datetime.datetime.now (). Strftime ("% Y-%m-%d") # determine whether the letter expires def checkDate (t): return t [0:10] = = today () # generate uuiddef randomKey (): return''.join (random.sample (' zyxwvutsrqponmlkjihgfedcba0123456789', 6)) # api gateway reply message format def apiReply (reply, html=False) Code=200): htmlStr = ritual writing a letter to your future self html, body {padding: 0px Margin: 0px; height: 100vh;} .main {display: flex; flex-direction: column; justify-content: center; align-items: center;} .main _ phone {display: flex; flex-direction: column; justify-content: start Align-items: center;} start writing letters

Start writing a letter

Date of delivery

Delivery let datex =''; let myEmail = document.getElementById ('email'); let myLetter = document.getElementById (' letter'); let myCalendar = document.getElementById ('calendar') Let width = window.innerWidth | | document.documentElement.clientWidth | | document.body.clientWidth let height = window.innerHeight | | document.documentElement.clientHeight | | document.body.clientHeight let pc = width > = height let today = new Date (); let info = today.toString () .split ('') Let selected = `${info [1]} ${today.getDate ()}, ${today.getFullYear ()}`; document.getElementById ('body') .classList.add (pc? 'main':' main_phone'); document.getElementById ('letter_left'). Style.display = pc? 'block':' none'; document.getElementById ('letter_top'). Style.display = pc? 'none':' block'; myCalendar.setAttribute ("selected", selected); myCalendar.addEventListener ('selected', () = > {let selectedObject = myCalendar.value; let date = new Date (new Date (). SetDate (selectedObject.date.getDate (); datex = date.toISOString (). Substr (0,10);}) Function send () {if (datex.length

< 1 || myEmail.value.length < 1 || myLetter.value.length < 1) { alert('信件内容、送信日期或投递邮箱不能为空'); return; } fetch_(window.location.href, { method: 'POST', body: JSON.stringify({ date: datex, email: myEmail.value, letter: myLetter.value }) }).then(res =>

Res.json () .catch (error = > console.error ('Error:', error)) .then (response = > alert (response.ok? 'add success:)': 'add failed: ('));}

If it is a GET request, return to the front page above, that is, the first picture at the beginning of the article, and take a look again.

Let's take a look at the sending process of the front-end web page.

Function send () {if (datex.length

< 1 || myEmail.value.length < 1 || myLetter.value.length < 1) { alert('信件内容、送信日期或投递邮箱不能为空'); return; } fetch_(window.location.href, { method: 'POST', body: JSON.stringify({ date: datex, email: myEmail.value, letter: myLetter.value }) }).then(res =>

Res.json () .catch (error = > console.error ('Error:', error)) .then (response = > alert (response.ok? 'add success:)': 'add failed: ('));}

Here, we POST a json string containing all the mail information to the current web address, which is also the api gateway address of the cloud function.

If event ['httpMethod'] = =' POST': # add letter body = json.loads (event ['body']) flag = addletter (body [' date'], body ['email'], body [' letter']) return apiReply ({'ok': True if flag else False,' message': 'added successfully' if flag else 'failed'})

Back to the backend of the cloud function, after receiving the POST request, we get the POST request body in event, convert the json string to the map object again, then pass the body to the addletter function, save the letter information in the cos, and reply to the front end of the web page whether the letter has been added successfully.

In this way, the front and rear ends of the whole application can be realized with only one cloud function, isn't it very sour?

Step 3: configure SCF triggers

Locate the template.yaml configuration file under the local cloud function folder

Resources: default: Type: 'TencentCloud::Serverless::Namespace' letter: Properties: CodeUri:. / Type: Event Environment: Variables: Description: write a letter to the future cloud function Handler: index.main_handler MemorySize: 64 Timeout: 3 Runtime: Python3.6 Events: timer: Type: Timer Properties: CronExpression:'08 * 'Enable: True letter_apigw: Type: APIGW Properties: StageName: release ServiceId: HttpMethod: ANY Type:' TencentCloud::Serverless::Function'

The names of cloud functions, timer triggers and api gateway triggers are mainly configured here, which can be set by yourself.

Step 4: launch the cloud function and enable response integration in the api gateway. Step 5: bind the licensed domain name above is how to write a letter to the future using SCF+COS based on Serverless. If you happen to have similar doubts, please refer to the above analysis for understanding. If you want to know more about it, you are welcome to follow the industry information channel.

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