Flask Note One (unit test, Debugger, Logger)

Source: Internet
Author: User

Flask Note One (unit test, Debugger, Logger)

Flask is a framework for developing web programs using Python. Rely on Werkzeug for full WSGI support, as well as JINJA2 to provide templates support. Flask's design philosophy is to provide a micro and convenient framework. "Micro" is because other functions, such as database access, are done through extension in addition to the implementation of the basic features. Convenient features are provided with the necessary features and functionality that are easy to use, and provide features that include:

    1. Built-in development server and debugging tools.
    2. Integrated unit test Support.
    3. Support for templates (dependent on JINJA2)
    4. Full WSGI support (dependent on WERKZEUG availability)
    5. Security Cookies and Sessions
    6. Thread-locals, such as the object within each request, is only meaningful within the thread.
Templates

Flask uses JINJA2 as the templates engine. The default syntax setting for JINJIA2 is as follows:

    • {% ...%} contains statements (logical processing code block)
    • {{ ... }} Contains expressions (output to tempalte statement)
    • {# ... #} contains comments (comments, statements that are not output to template)
    • # # # contains single-line statements (single-line processing code block)
Unit Test

Flask provides a very simple way to create a context for testing (Local contexts) through test_client. This can be done in a variety of ways to complete unit testing, the most basic way is to complete the integrated test case through the unittest of Python.

UnitTest

The framework for Flask unit testing using UnitTest is as follows:

import osimport xxxximport unittestimport tempfileclass XxxxTestCase(unittest.TestCase):    def setUp(self):        self.db_fd, xxxx.app.config[‘DATABASE‘] = tempfile.mkstemp()        xxxx.app.config[‘TESTING‘] = True        self.app = xxxx.app.test_client()        xxxx.init_db()    def tearDown(self):        os.close(self.db_fd)        os.unlink(xxxx.app.config[‘DATABASE‘])if __name__ == ‘__main__‘:    unittest.main()

In the above example:

    1. XXXX is a custom simple flask program, Xxxx.app is a flask class object that corresponds to a Web application.
    2. Inside the setup function, the testing parameter of the Flask Web application is configured to True and a corresponding test client (test_client) is created, containing the context that the test requires.
    3. In the Setup function, the database file of XXXX was created and initialized.
    4. Inside the teardown function, the database file is closed and deleted.
      The function that tests the use case in UnitTest must start with the test word, for example testFunc1 , so that the test framework can execute the function as a test case. Executes the setup function to initialize before executing the test case, and then executes teardown for resource release. The basic test cases are as follows:

      def testemptydb (self):
      RV = Self.app.get ('/')
      Assert ' No entries here, ' in Rv.data

Local Context

The UnitTest framework creates the testclient and the required context through setup and destroys it within the teardown function. You can also use the testclient to complete validation tests in arbitrary code. Because Test_client creates a temporary context, it can be used in any region through the WITH statement, so the request and session information can be verified within this scope.
A simple example of verifying the request information:

with app.test_client() as c:    rv = c.get(‘/?number=42‘)    assert request.args[‘number‘] == ‘42‘

A simple example of verifying session information:

with app.test_client() as c:    rv = c.get(‘/‘)    assert flask.session[‘foo‘] == 42

If you need to modify thesession information in the temporary context created by test client, you can use the sessionTranscation to get the session object to be modified. Here's a simple example:

with app.test_client() as c:    with c.session_transcation() as sess:        sess[‘a_key‘] = ‘a value‘
Debug&logging

In the program, errors can never be avoided, errors may be code logic problems, server problems, network problems or hardware problems, environmental issues and so on. Flask provides two ways to locate the problem, one can open the program debug mode, through the debugger (debugger) Tracking program execution information, in addition flask provides a complete log system, recording program operation information.

Debug

Flask uses the necessary parameter settings to determine whether to use debug mode and whether to use a self-brought debugger. These parameters include:

    • Debug True: Set debug mode; False: Non-debug mode
    • Use_debugger. True: Use the internal debugger; Flase: not Practical Internal debugger
    • Use_reloader. True: Whether the current process of reload and fork is debugged while excpetion; False:nothing.

If you are using a third-party debugger like Aptana/eclipse, you need to set debug to True,usedebugger anduse Reloader to False.

Through the built-in debugger, when the program appears exception, the error interface provides an interactive interface, and in this interface can execute arbitrary code for program debugging. There is a huge security risk, so you should never turn on debug mode on the product server .

Logging

The logger included with flask relies on Python's built-in journaling system, which sets the processing handler, log format, and level of processing through the default logging library. The log written by flask logger in the program is filtered and formatted by the system's own logging system, and then output to the handler set.

handler can be a file or a message, the general scenario is to save most of the log information to a file and send the log information that focuses on the messages to the message.

    • File handler. File handler contains four kinds:

      • Filehandler, a file that corresponds to the file system.
      • Rotatingfilehandler, which corresponds to a file system file, after outputting a certain amount of information, start over.
      • Nteventloghandler, which corresponds to the logging system of the Windows operating system.
      • Sysloghandler, corresponding to the UNIX syslog system.
    • Mail handler. Mail is usually sent using Smtphandler.

    • A simple example of handler is as follows:

      If not app.debug:
      Import logging
      From Logging.handler import Smtphandler, Filehandler

      file_handler = FileHandler(/var/test/flask.log)file_handler.setLevel(logging.WARNING)email_handler = SMTPHandler(‘127.0.0.1‘,                            ‘[email protected]‘                            ADMINS,                            ‘Your Application Failed!!!‘)app.logger.addHandler(file_handler)app.logger.addHandler(email_handler)

Formatter is a python-provided log system that allows you to set the format of information you need to save for handler. In general, a detailed multiline text message is saved in the message handler, and a single line of important information is saved in the file handler. The format parameters of log are as follows:

    • % (levelname) s | | Log level (contains: ' DEBUG ', ' INFO ', ' WARNING ', ' ERROR ', ' CRITICAL ') | |
    • % (pathname) s | | Log generated source file path | |
    • % (filename) s | | Log generated source file name | |
    • % (module) s | | Log Generated Module | |
    • % (funcName) s | | Function name generated by log | |
    • % (Lineno) d | | Log generated by the file line number | |
    • % (asctime) s | | The time format generated by log is: Yyyy-mm-dd hh-mm-ss, MMM (, followed by milliseconds)
    • % (message) s | | Log Information | |

Simple example of email log format setup:

from logging import Formattermail_handler.setFormatter(Formatter(‘‘‘    Message type:       %(levelname)s    Location:           %(pathname)s:%(lineno)d    Module:             %(module)s    Function:           %(funcName)s    Time:               %(asctime)s    Message:            %(message)s‘‘‘))

A simple example of file log format settings:

from logging import Formatterfile_handler.setFormatter(Formatter(    ‘%(asctime)s %(levelname)s: %(message)s ‘    ‘[in %(pathname)s:%(lineno)d]‘    ))

The third library used in flask has its own logging policy, and you can also use GetLogger to get logger of each dependent library to set a unified handler. The following example:

from logging import getLoggerloggers = [app.logger, getLogger(‘sqlalchemy‘),           getLogger(‘otherlibrary‘)]for logger in loggers:    logger.addHandler(mail_handler)    logger.addHandler(file_handler)

Flask Note One (unit test, Debugger, Logger)

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.