Small program in January 2017 online at the beginning, was highly touted by the society, deliberately to make it a “tuyere”, overdraft its value. But over the next month, The rock quickly fell silent. The media began to overconsume small programs again, talking about their shortcomings.

Personally, I think a watershed for Mini program came on December 28. Wechat is upgraded to version 6.6.1, and the small program entry is transplanted to the main interface. You can choose to enter the main interface by pulling down, and a new category of “small games” is supported. Small programs are heating up and playing an increasingly important role in the whole wechat ecosystem. Today, small programs are in the ascendance, and good small programs are easy to finance. Is this just another bubble, or is miniprograms themselves truly coming of age? I personally believe the latter.

I personally have done two small procedures, small procedures have a certain understanding, but the understanding is relatively shallow. Today, just from how to quickly build a small program to talk about, open a small program mysterious veil.

An overview of the

  • Applets are front – and back-separated.
  • The front end uses a set of specifications customized by wechatwxml+wxss+json+jsI think the essence is stillhtml+css+js.
  • The background can be used in any language you are familiar with:Java.Python.PHP.RubyWait, in this article I choosePythontheFlaskFrame +Gunicorn+NginxTo build quickly.
  • Database I chooseMySQL, NOSQL database I chooseRedis. Of course, your small program can be lightweight and doesn’t even need to use a database. Small program big idea “run out of time”.
  • The backend needs to run on its own server, and you also need a registered onehttpsDomain name to map.

note

There are also third-party tools on the market for generating applets quickly, in the same business as those used to generate websites quickly. I personally don’t recommend using them, because they’re almost identical, they don’t incorporate your own ideas, they don’t customize the services you need to provide, and there are bound to be some fees.

Of course, since these platforms exist, it must be market demand so, if suit you really, can bring a few benefits for you, might as well try.

Today, we are building applets from a learner’s point of view.

The preparatory work

  1. A cloud server can be rented from the platforms of major cloud providers. I use the student low allocation at ¥10/ month.
  2. The operating system I use on the server isubuntu
  3. Buy a domain name and put it on record. Domain name prices range from 1 to 10000000, I use acomDomain name, ¥50/ year.
  4. Register an account on the wechat public platform and download the mini program development tool. Detailed instructions
  5. fromhttptohttps. Many SSL certificates are now free to apply for, but the following details how to configure them.

The target

Our goal is to achieve a simple small program, can achieve the back end docking.

From HTTP to HTTPS

  1. First, you have a registered domain name that has been resolved to your server.
  2. If you rent a server in Alibaba/Tencent cloud, you can apply for a free SSL certificate. Just find the appropriate entrance and apply. Reviews are usually quick. Mine was under an hour.
  3. After the certificate is approved, download the issued certificate and save it to the local PC. The FTP file is then uploaded to the corresponding path of the server.
  4. Install it on the serverNginx.
  5. First, test whether your Nginx service can run properly. After configuring your domain name to display the welcome page of Nginx, the configuration will be successful.
  6. Then upload your certificate via FTP to any path on the server (recommended andNginxUnder the same path)
  7. Open theNginxAs shown in the figure (certificate path fill in your own)
  8. Restart the service. If the browser can access the service using HTTPS and the page can be displayed properly, the configuration is successful.

The front end

Now open your applets development tool and create a new project using your APPID. (I don’t have any extra APPids here, so USE the test environment first)

To generate an official test demo, select “Create normal Quick start Template”, as shown below:

Let’s look at the directory structure. App.js,app.json, and app.wxss correspond to global methods, global configuration parameters, and global styles respectively. And under the specific package index. Js, index. WXML, index. WXSS is corresponding to the corresponding elements.

Now let’s write some simple page code.

<! -- index.wxml --> <view class="main-card">
 <view class="main-card-item" id="toast" wx:if="{{news_flag}}">
    <view class="card-item-hd" >
      <image class="card-item-icon" src="/images/index/toast.png"></image>
      <text class="card-item-name"> </text> </view> <view class='toast'> < p style = "max-width: 100%; clear: both; min-height: 1em; </view> </view> </view>Copy the code
/* index.wxss */

page {
  background-color: #f8f8f8;
}

.main-card {
  padding-bottom: 100rpx;
}
.main-card-item{
  display: flex;
  flex-direction: column;
  background: #fff;
  border-top: 1rpx solid #F6F6EF;
  border-bottom: 1rpx solid #F6F6EF;
  margin-bottom: 20rpx;
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: bottom center;
  overflow: hidden;
  margin-left: 12rpx;
  margin-right: 12rpx;
   border-radius: 15rpx;
}

.card-item-hd{
  display: flex;
  align-items: center;
  height: 75rpx;
  border-bottom: 1rpx solid #e5e5e5;
  margin-left: 30rpx;
}
.card-item-icon{
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}
.card-item-name{
  letter-spacing: 1px;
  font-size: 25rpx;
}
.toast{
  
  letter-spacing:3rpx;
  line-height: 50rpx;
  font-size: 28rpx;
  margin-left: 20rpx;
  margin-top: 20rpx;
  margin-bottom: 40rpx; 
  
}
Copy the code

At this point, a simple page has been generated, and let’s see what it looks like.

It’s simple, but you can see that the content in “Big Things” is written dead, and we need the back end to provide the data.

## server environment

Before writing the back end, let’s deploy the server environment.

Installation:

  1. The Python environment is installedapt-get install python-dev
  2. Install the Flaskpip install flask
  3. Install UWSGIpip install uwsgi
  4. Install Nginxapt-get install nginx
  5. Install the Gunicornpip install gunicorn

To prepare

Start by creating a test directory in your /var/www/ directory, such as /var/www# mkdir test

Then use chmod to change the permission of this directory chmod 777 /var/www/test

Here are the rules for CHmod, and since this is a test case, we’ll just use 777 for convenience.

Nginx

The directory structure for Ubuntu Nginx is as follows:

  1. All the configuration files are there/etc/nginxEach virtual host has been scheduled/etc/nginx/sites-availabledirectory
  2. The startup program file is in/usr/sbin/nginx
  3. The log file is placed/var/log/nginxIn, respectivelyaccess.loganderror.log
  4. in/etc/init.d/The startup script nginx was created under
  5. The default virtual host directory is set to/usr/share/nginx/www

D /nginx start :/etc/init.d/nginx restart

Now we need to go into the Nginx configuration and change the configuration file. vim /etc/nginx/site-avalidable/default

D /nginx restart or service nginx restart after changing the configuration file

Gunicorn

Gunicorn Green Unicorn is a Python WSGI UNIX HTTP server. This is a pre-fork worker model, ported from Ruby’s Unicorn project. The Gunicorn server is broadly compatible with a variety of Web frameworks, requiring very simple execution, lightweight resource consumption, and is quite fast.

At this point, we need to put the test directory created in the “Prepare” step into our test run project. The FTP tool I choose is: XFTP. I passed in a simple Python file wsgi.py for testing, previewing it with the command /var/www/myflask# vim wsgi.py.

At this point, type the command gunicorn -w 4 -b 127.0.0.1:8000 in the test directory to run wsgi:app.

At this point, you can visit the server and see that “Hello World” is displayed normally.

About the Flask

For the backend, we use Python’s Flask framework +Gunicorn+Nginx to build it quickly. First of all, you need some basic knowledge of Python, which is not a problem at all. Now, let’s see how Flask works.

A software engineer with more than a decade of experience developing complex applications in multiple languages, including PHP, Ruby, Smalltalk and even C++, thinks the Python/Flask combination is the most liberating of all.

After using the Flask, I have to admit that it’s really quick and handy. Of course, there will be certain disadvantages, that is later.

Back to business.

Get the object

from flask import Flask

app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World'

if __name__ == '__main__':
    app.run() 
Copy the code

This is the simplest Demo.

The execution process is as follows: obtain the object APP from the flask module, route, execute the method, and return the content.

At this time, access the browser (default port 5000) : 127.0.0.1:5000 /, you can see the interface of international convention Helloworld.

routing

  • The only URL:
@app.route('/hello')
@app.route('/hello/')
# These two types need to be distinguished
#
@app.route('/hello/')
If the user does not enter a trailing slash (/), the user will get to the correct page
#
@app.route('/hello')
If the user enters a slash at the end of the url, 404 will be returned
Copy the code

This rule may seem like a mouthful, but it’s also incomprehensible. Advantages are:

  1. This allows the associated URL to take over when the user forgets the trailing slash, just as Apache and other servers do
  2. This ensures that the URL is unique and helps prevent search engines from indexing the same page twice.

If you really don’t remember, the best way is to break the jar and break it: unified without the tail “/”

  • Construct the dynamic part of the URL
@app.route('/var/<name>')
def var(name):
    return 'hello'+' '+name
Copy the code

I don’t need to go over this point, but let’s take a look at the demo:

Template rendering

Most of the time we need to return an interface to the user when he or she accesses a URL, and of course we don’t render HTML in Python itself, for which Flask has a Jinja2 template engine.

After looking at the following code examples, I’m sure you’ll understand.

First, we create the “Templates” folder to hold the templates.

Flask looks for templates in the Templates folder. So, if your application is a module, this folder should be the same level as the module; If it is a package, then this folder acts as a subdirectory of the package:

# Case 1: Module:
/application.py
/templates
    /hello.html

# Situation 2: Package:
/application
    /__init__.py
    /templates
        /hello.html
Copy the code
  1. Example without arguments in program execution:
@app.route('/redi/')
def redi():
    return render_template('hello.html')
Copy the code

  1. Let’s look at another example, adding dynamic parameters:
@app.route('/redi2/<name>')
def redi2(name):
    return render_template('hello2.html',name=name)
Copy the code

The GET and POST

There are more than two methods of requesting things, but these are the most common. If you are not familiar with these methods, you can look up HTTP methods, which are only used in flask.

@app.route('/met',methods=['GET'.'POST'])
def met():
    if request.method=='GET':
        return 'Here's the get method'
    if request.method=='POST':
        return 'This is the post method'
Copy the code

Open the Software Postman (Web artifact) and simulate sending HTTP requests.

The request object

Let me simulate a simple login operation.

The first is the controller:

@app.route('/login',methods=['POST'.'GET'])
def login():
    error=None
    if request.method=='POST':
        print (request.form['username'] +' '+request.form['password'])
        if func.login_func.valid_login(request.form['username'],
                    request.form['password') :return func.login_func.login_success(request.form['username'])
        else:
            error='Invalid username/password'
            return render_template('login_error.html',error=error)
Copy the code

You can see the execution flow:

  1. Get the request
  2. Determine the request type
  3. Get login data
  4. The valid_login () method validates the login. 4.1 If the login is successful, perform the login_success () method. 4.2 If the login fails, add failure information and return the failed template

Here are the two methods used above:

def valid_login(username,password):
    if username=='admin' and password=='admin':
        return True
Copy the code
def login_success(username):
    return render_template('login_success.html',username=username)
Copy the code

Let’s use Postman to simulate the request and see if we can return the desired result.

Here are some simple Flask operations, ok, we now have some knowledge of the Web. Let’s start writing our code.

### the back end is ready. Let’s start by writing two routes, one for updating notifications and one for getting notifications.

@app.route("/updateToast",methods=['POST'])
@allow_cross_domain
def update_toast():
    data=db_util.update_toast(request.form['toastUpdateInfo'])
    return jsonify(data)

@app.route("/getToast",methods=['GET'])
@allow_cross_domain
def get_toast():
    data = db_util.get_toast_info()
    return jsonify(data)

Copy the code

Then write a utility class that works directly with the database (this is not intended as a specification, just for a quick demonstration)

#db_util.py
def get_toast_info():
    db = pymysql.Connect(
        host='xxx',
        port=3306,
        user='xxx',
        passwd='xxx',
        db='xxx',
        charset='utf8'
    )
    cursor = db.cursor()
    sql = "select content from guohe_lite_toast order by id desc limit 1 "
    try:
        cursor.execute(sql)
        result = cursor.fetchone()
        return response_info.success('Applet notification query successful', result)
    except:
        return response_info.error('2'.'Applet notification query failed', result)
        Close the database connection
    finally:
        db.close()
def update_toast(toast_update_info):
    db = pymysql.Connect(
        host='xxx',
        port=3306,
        user='xxxx',
        passwd='xxx',
        db='xxxx',
        charset='utf8'
    )
    cursor = db.cursor()
    sql = "insert into guohe_lite_toast(content,update_time) values(%s,%s) "
    try:
        dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cursor.execute(sql,(toast_update_info,dt))
        db.commit()
        return response_info.success('Notification update successful', toast_update_info)
    except:
        db.rollback()
        return response_info.error("2".'Update failed', toast_update_info)
    finally:
        db.close()
Copy the code

Now, let’s use Postman to test the interface.

First, update the notice:

Then see if you can successfully obtain:

It’s all working, and the data interface is ready.

Data rendering

Now, how do you get data and display it on the applet side? Let’s briefly read the official documentation of the applet.

Note that the applets send requests in a purely asynchronous fashion.

Let’s imitate it:

#index.js
wx.request({

      url: 'https://example.com/getToast',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'// Default value}, success:function (res) {
        var message = res.data.info[0]
        console.log(message)
        that.setData({
          toast: message
        })
      }

    })
Copy the code

Having saved the data in the variable “toast”, read the document to see how the applet does the data binding. Then we replace the dead text with “{{toast}}”, then refresh, and see that the data is displayed.

<! -- index.wxml --> <view class="main-card">
 <view class="main-card-item" id="toast" wx:if="{{news_flag}}">
    <view class="card-item-hd" >
      <image class="card-item-icon" src="/images/index/toast.png"></image>
      <text class="card-item-name"> </text> </view> <view class='toast'>
    {{toast}}
    </view>
  </view>
</view>
Copy the code

At this point, a complete process has been completed, although a tiny function has been achieved, but the sparrow is small, all five organs. The next step is to further learn how to transform and enrich our program.

Like a little effort: