Compile the program for creating logs in the Python web framework

Source: Internet
Author: User
This article describes how to compile a log creation program in the Python web framework. the sample code is based on Python2.x. For more information, see Web development, back-end code is actually quite easy to write.

For example, we compile a rest api to create a Blog:

@api@post('/api/blogs')def api_create_blog():  i = ctx.request.input(name='', summary='', content='')  name = i.name.strip()  summary = i.summary.strip()  content = i.content.strip()  if not name:    raise APIValueError('name', 'name cannot be empty.')  if not summary:    raise APIValueError('summary', 'summary cannot be empty.')  if not content:    raise APIValueError('content', 'content cannot be empty.')  user = ctx.request.user  blog = Blog(user_id=user.id, user_name=user.name, name=name, summary=summary, content=content)  blog.insert()  return blog

Writing back-end Python code is not only simple, but also very easy to test. the above API: api_create_blog () itself is just a common function.

The real difficulty of Web development lies in the preparation of front-end pages. Front-end pages need to be mixed with HTML, CSS, and JavaScript. if you do not have a deep understanding of the three, it will be difficult to maintain the prepared front-end pages soon.

The bigger problem is that the front-end page is usually a dynamic page, that is, the front-end page is often generated by the back-end code.

The earliest way to generate a front-end page is to splice strings:

s = '' + title + '' + body + ''

Obviously, this method does not have maintainability at all. Therefore, there is a second template method:

  {{ title }}  {{ body }}

ASP, JSP, and PHP all use this template to generate front-end pages.

If JavaScript is used heavily on the page (in fact most pages), the template method will still cause the JavaScript code to be closely bound with the back-end code, making it difficult to maintain it. The root cause is that the html dom model for display is not clearly separated from the JavaScript code for data and interaction.

It is not easy to write maintainable front-end code. The MVC mode combined with the backend can no longer meet the needs of complex page logic. Therefore, the new MVVM: Model View ViewModel mode emerged.

MVVM was first proposed by Microsoft. it draws on the MVC idea of desktop applications and represents the Model on the front-end page with a pure JavaScript Object:

《script》var blog = {  name: 'hello',  summary: 'this is summary',  content: 'this is content...'};《script》

View is pure HTML:

 

Because the Model represents data, the View is responsible for display, and the two are separated to the maximum extent.

The ViewModel is associated with the View. ViewModel is responsible for synchronizing the data of the Model to the View display, and synchronizing the modification of the View back to the Model.

How to compile ViewModel? A general ViewModel needs to be written in JavaScript, so that the entire MVVM model can be reused.

The good news is that there are many mature MVVM frameworks, such as AngularJS and KnockoutJS. We chose Vue, an easy-to-use MVVM framework, to create a Blog page templates/manage_blog_edit.html:

{% Extends '{base=.html '% }{% block title %} edit log {% endblock % }{% block beforehead %} script var action =' {action }}', redirect = '{redirect}'; var vm; $ (function () {vm = new Vue ({el: '# form-blog', data: {name: '', summary:'', content: ''}, methods: {submit: function (event) {event. preventDefault (); postApi (action, this. $ data, function (err, r) {if (err) {alert (err);} else {alert ( 'Saved successfully! '); Return location. assign (redirect) ;}}}}) ;}); script {% endblock %}{ % block content %}

{% Endblock %}

When initializing Vue, we specify three parameters:

El: search for the bound View based on the selector. here is # form-blog, which is the DOM with the id of form-blog, which corresponds to

Tag;

Data: The Model represented by the JavaScript Object. We initialize it to {name: '', summary:'', content :''};

Methods: View can trigger JavaScript functions. submit is the function triggered when a form is submitted.

Next, weIn the tag, use a few simple v-models to associate the Vue with the View:

  

Form passedAssociate the form submission event with the submit method.

In MVVM, the Model and View are bound in two directions. If we modify the text box value in Form, we can get the new value in Model immediately. Try entering text in the form and open the JavaScript console in the Chrome browser. you can access a single attribute through vm. name or access the entire Model through vm. $ data:

If we modify the Model in the JavaScript logic, this modification will be immediately reflected in the View. Try entering vm. name = 'mvvm Introduction' on the JavaScript console. you can see that the content of the text box is automatically synchronized:

Two-way binding is the biggest role of the MVVM framework. With MVVM, we handed over the complex display logic to the framework. Since the backend has compiled an independent rest api, it is very easy for the front end to submit forms using AJAX, and the front and back ends are completely separated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.