This article is< Python + wechat applet development from scratch >The ninth column mainly introduces the latest and complete introduction to cloud development, wechat applet cloud development, cloud function, cloud database learning, wechat applet cloud development and extended function learning. I hope you can learn together and communicate with each other.
1, Understanding applet cloud development
1. Introduction to cloud development
- Applet cloud development is a professional applet development service launched by wechat team and Tencent cloud.
- Developers can use cloud development to quickly develop small programs, games, official account pages, and so on, and open up WeChat's original capability.
- Developers do not need to build a server and can directly use the API provided by the platform for business development without authentication.
Cloud development provides three basic capabilities to help developers quickly develop small programs:
- Cloud function: developers can write functions according to business needs and deploy them in the cloud, which can be called in applets. Developers do not need to maintain complex authentication mechanisms, nor do they need to buy and build servers, so they can easily complete small program development.
- Database: developers can read and write the database directly in the applet front end or cloud function, and support data management through the cloud console in the developer tool.
- Storage management: developers can quickly realize file upload / download and management functions at the front end of the applet, and can also manage them in the developer tool "cloud development" console.
Official documents: Wechat open document
2. Comparison between cloud development and traditional servers
Through the above clear comparison, we can see that if a small team wants to quickly create a background of small programs, cloud development is a good choice.
2, Creation and initialization of cloud development environment
Today, we will formally create our first cloud development project. Before creating cloud development, there are the following precautions
- You must register an applet before you can open cloud development
- An applet can create two cloud development environments
Registration applet process can refer to Python + wechat applet development (I) understanding and environment construction.
1. Create an initial project
To open the cloud development service, you must first enter the applet developer tool. When the developer tool creates a project, select wechat cloud development, select no template in the template selection, and fill in your own AppID.
2. Open Cloud Development
2.1 click cloud development
2.2 name the cloud development environment
2.3 obtaining cloud development environment id
Record your cloud development environment id.
3. Initialize the cloud development environment
Write the environment id in app.js. Note that your own cloud development environment id should be used here.
App({ onLaunch: function () { if (!wx.cloud) { console.error('Please use 2.2.3 Or above to use cloud capabilities') } else { wx.cloud.init({ // env Parameter Description: // The env parameter determines which cloud environment resources will be requested by default for the next cloud development call (wx.cloud.xxx) initiated by the applet // Please fill in the environment ID here. You can open the cloud console to view the environment ID // If it is not filled in, the default environment (the first created environment) will be used env: 'Your environment id', traceUser: true, }) } this.globalData = {} } })
3, Cloud development database
Refer to official documents: Cloud development database.
1. Create a new set in the database
Let's create a new product list as an example.
2. Create a new record in the collection
Two new records are created. The fields are name and price, which are {apple, 10} and {banana, 15} respectively.
3. Database permission management
If you want users to query the commodity data we created, you need to change the permission to be readable by all users.
3. Addition, deletion, modification and query of database
First, create a new goods page.
Add in pages/goods/goods.js:
const db = wx.cloud.database()
three point one Query get()
enquire(e){ let that =this db.collection('goods').get({ success: function(res) { // res.data is a data that contains all records in the collection that have access rights, no more than 20 that.setData({ list:res.data }) console.log(res.data) } }) },
3.2 add data
insert(e){ let that =this db.collection('goods').add({ data:{ name:'Pear', price:'15' }, success: function(res) { // res is an object in which_ The id field marks the id of the record just created console.log('Added successfully',res) } }) },
3.3 update data
change(e){ let that =this db.collection('goods').doc('9e7190f16183f44003b4a35f7560aa65').update({ data:{ price:'30' }, success: function(res) { // res is an object in which_ The id field marks the id of the record just created console.log('Change succeeded',res) } }) },
3.4 delete data (remove)
delete(e){ let that =this db.collection('goods').doc('859059a56183f48803c02801607c0563').remove({ success: function(res) { // res is an object in which_ The id field marks the id of the record just created console.log('Delete succeeded',res) } }) },
4, Cloud development cloud function
1. Understand cloud function
Refer to official documents: Cloud development cloud function
In short, cloud functions run on the server, but compared with our traditional development language. Wechat official provides us with a fool's one click deployment. In other words, you only need to focus on the preparation of business logic code, and you don't need to care about how to deploy, security or authentication.
For example, the cloud function obtains openid:
With the cloud function, it only takes 3 steps
- Writing cloud functions
- One click deployment of cloud functions
- Call cloud function
Let's look at the cloud function code. It only needs 10 lines of code, which can be easily done.
2. Advantages of cloud function
We compare the cloud function with the cloud database in the previous chapter.
operation | Cloud function | Cloud database |
---|---|---|
Return data upper limit | 100 articles | Article 20 |
Update data | Can be updated | Only self created can be updated |
Delete data | Can be deleted | Only self created can be deleted |
Operating environment | Run in cloud Node.js environment | Run locally in applet |
Achieve functional richness | Very rich | You can only add, delete, modify and query the database |
The cloud function belongs to the management side. The code running in the cloud function has unrestricted database read-write permission and cloud file read-write permission. It should be noted that the cloud function operating environment is the management side, which has nothing to do with whether the wechat user corresponding to the openId passed in the cloud function is the administrator / developer of the applet.
3. Cloud function call demonstration
three point one Environment for initializing cloud functions
First select the cloud development environment.
If it cannot be detected automatically, you can first upload login cloud functions - > upload failed, prompting that you need to configure the cloud environment - > right click the cloudfunctions folder - > select the environment.
Then click save. There is a cloud in front of our cloudfunctions folder, which means that our cloud functions have been initialized successfully.
3.2 create a new cloud function
After initialization, it is automatically generated in cloudfunctions/getData/index.js:
// Cloud function entry file const cloud = require('wx-server-sdk') cloud.init() // Cloud function entry function exports.main = async (event, context) => { const wxContext = cloud.getWXContext() return { event, openid: wxContext.OPENID, appid: wxContext.APPID, unionid: wxContext.UNIONID, } }
3.3 cloud function data acquisition
Then add the following in pages/goods/goods.js:
let that = this wx.cloud.callFunction({ name:'getData', success(res){ console.log('Cloud function requested successfully','res') that.setData({ openid:res.result.openid }) console.log(openid) } })
5, Cloud development cloud storage
1. Understand cloud storage
In short, cloud storage is a cloud storage space that can be used to store video, audio, pictures and files. If your applet needs video playback, audio playback, picture display, file upload and download functions, you can use our cloud storage.
- When using cloud storage to store files, there are some rules for naming file names. It is recommended to take a look.
File name naming restrictions
- Cannot be empty
- Cannot start with /
- No continuity/
- The maximum encoding length is 850 bytes
- It is recommended to use upper and lower case English letters and numbers, i.e. [A-Z, A-Z, 0-9] and symbols -* And its combination
- Characters above (↑), below (↓), right (→) and left (←) in ASCII control characters are not supported, corresponding to CAN(24), EM(25), SUB(26) and ESC(27) respectively
- If the name of the file or folder uploaded by the user is in Chinese, when accessing and requesting the file or folder, the Chinese part will be converted into a percentage code according to the URL Encode rules.
- Special characters not recommended: ` ^ "\ {} [] ~% # \ > < and ASCII 128-255 decimal
- Special characters that may be used after special processing::; = & $@ +? (space) and ASCII character range: 00-1F hexadecimal (0-31 decimal) and 7F (127 decimal)
2. Cloud development console management files
The console can also easily manage files.
3. Upload pictures to cloud storage
Callable on applet side wx.cloud.uploadFile Method to upload:
wx.cloud.uploadFile({ cloudPath: 'example.png', // Path uploaded to the cloud filePath: '', // Applet temporary file path success: res => { // Return file ID console.log(res.fileID) }, fail: console.error })
After successful upload, you will get the unique identifier of the file, that is, the file ID. subsequent operations are based on the file Id rather than the URL.
It also includes functions such as downloading files, deleting files, exchanging temporary links, etc. for details, please refer to: Cloud storage API guidelines.
6, Summary
This article is a learning experience of wechat applet cloud development. It mainly introduces the simple use of cloud database, cloud function and cloud storage. For further in-depth learning, please look forward to the next article.