Example of using REST APIs in Python Web-creating your own online translation tools based on cloud platforms and cloud services

Source: Internet
Author: User

Example of using REST APIs in Python Web-creating your own online translation tools based on cloud platforms and cloud services

As a programmer, he may be learning technology and new developments in the industry. When solving problems, he often needs to read English content. An English like me can only use translation tools to understand a rough idea; I can't help but feel that English is too important for learning computer knowledge! I recently found that IBM's cloud platform Blumemix provides language translation services. I feel good, so I will study it. Here I will share my study process, how to Use Python to call the rest api to create your own online translation tool and demonstrate how to publish it to the cloud platform so that everyone can access it through the network.

Application Effect display

You can access the slice by clicking the link of the slice.

 

A Bluemix account is a prerequisite for building a similar application, you do not have? Click here to register, there are already, click here to log on;

 

Basic understanding of HTML (Hypertext Markup Language;

Basic understanding of CSS (Cascading Style Sheets;

Basic understanding of JavaScript (a literal scripting language;

Basic understanding of the Python language;

Basic understanding of Python Web programming;

I provide all the necessary code, but a basic understanding of these technologies helps you understand the details.

Step 1. Create Your Python application

 

% S
  1. 1. Go to "dashboard" on the Bluemix user interface ".
  2. 2. Click Create application.
  3. 3. Click Web, select the entry template based on the guidance experience, specify the name, and select the encoding method.
  4. Enter the application name
  5. The Application name is unique. Next, use it as a second-level domain name to access your application!
  6. After clicking finish, wait for a while and then you can see the interface
  7. Then you can access the application you just created. For example:

  8.  

    Step 2. Add the Language Translation Service
    1. You can click Add service or API on the application "Overview" in the Bluemix user interface to add the service to the application. You can also use the cf command line interface. See available options for processing applications.
    2. Select Language Translation in the service list)
    3. You can specify the service name or use the default one;
    4. Obtain Service Information

      Go to the application overview page, find the added service, and click "show creden”" to view the service details:

      Access the service URL in a browser, for example:

     

     

    Step 3. Prepare the development environment step 4. write code 1. Download the initial Hello World sample code

    Go to your application, click Start encoding on the left, and click Download getting started template code on the right ".

    2. Make it run locally

    1. decompress the downloaded entry template code to a directory, open the command line window, and switch to this directory.

    2. Execute the command: python server. py

    3. Access http: // localhost: 8000/in a browser/

     

    3. write code

    Main front-end AJAX code: Call the background translation processing program to achieve user interaction

     

    [Javascript]View plaincopy
    1. // Call the background translation program through AJAX
    2. Function doExecTrans (){
    3. Var txt = $ ("# InputText"). val ();
    4. If (txt = ""){
    5. Alert ("Enter the text to translate! ");
    6. Return;
    7. }
    8.  
    9. $ ("# ProgressDiv"). show ();
    10. $. Ajax ({
    11. Type: "GET ",
    12. Url: "trans ",
    13. DataType: "json ",
    14. Data: {"txt": txt },
    15. Success: function (data ){
    16. $ ("# ProgressDiv"). hide ();
    17. Console. log (data );
    18. If (data. error ){
    19. Alert (data. error );
    20. } Else {
    21. $ ("# OutputText"). text (data. text );
    22. }
    23. },
    24. Error: function (data ){
    25. Console. log (data); ssss
    26. Alert ("Error Msg:" + data );
    27. $ ("# ProgressDiv"). hide ();
    28. }
    29. });
    30. }

    Main background code: server. py, interaction with Translation Service Web Service

     

    Import OS # The OS module in the Python standard library contains the general operating system function import re # introduce the regular expression object import urllib # used to codec the URL import sys # provides many functions and variables to process different parts of the Python runtime environment. import urllib2 # used to simulate HTTP/HTTPS requests # debug functions, used to output object attributes and attribute values def getAllAttrs (obj): strAttrs = ''for o in dir (obj ): strAttrs = strAttrs + o + ': =' + str (getattr (obj, o) + ''return strAttrs; try: from SimpleHTTPServer import SimpleHTTPRequestHandler as Handler from SocketServer import TCPServer as server‑t ImportError: from http. server import SimpleHTTPRequestHandler as Handler from http. server import HTTPServer as Server # Custom Handler used to process HTTP request class TransHTTPHandler (Handler): # process GET request def do_GET (self): # templateStr ='
    '# Compile the regular expression into the Pattern object pattern = re. compile (R'/trans \? Txt \ = (. *) ') # use Pattern to match the text and obtain the matching result. If the match fails, None match = pattern is returned. match (self. path) if match: params = {'source': 'en', 'target': 'els', 'text': match. group (1)} surl = 'https: // gateway.watsonplatform.net/language-translation/api/v2/translate? '+ Urllib. urlencode (params) resContent = ''try: passman = urllib2.HTTPPasswordMgrWithDefaultRealm () # create a Domain Verification object passman. add_password (None, surl, "Translation Service User Name", "password") # Set the domain address, user name and password auth_handler = urllib2.HTTPBasicAuthHandler (passman) # generate the handler for processing authentication with remote hosts opener = urllib2.build _ opener (auth_handler) # Return an openerDirector instance urllib2.install _ opener (opener) # Install an openerDirector instance as the default initiator. Response = urllib2.urlopen (surl) # Open the URL link and return the Response object resContent = response. read () # read response content failed T: info = sys. exc_info () resContent = getAllAttrs (info [0]) + getAllAttrs (info [1]) # obtain exception details self. protocal_version = 'HTTP/1.1 '# sets the Protocol version self. send_response (200) # Set the response status code self. send_header ("Content-type", "text/html") # sets the Response Header self. end_headers () self. wfile. write ("{\" text \ ": \" % s \ "}" % resContent) # output a request other than the response content else: #/trans, to the underlying layer to process if self. path = "": self. path = '/index.html' fStatic = self. send_head () if fStatic: try: self. copyfile (fStatic, self. wfile) finally: fStatic. close () # Read port selected by the cloud for our application PORT = int (OS. getenv ('Port', 8000) # change the current directory to the static directory OS. chdir ('static ') httpd = Server ("", PORT), TransHTTPHandler) try: print ("Start serving at port % I" % PORT) httpd. serve_forever () # Set to keep listening and receive requests except KeyboardInterrupt: pass # press Ctrl + C to exit the httpd service. server_close () The do_GET handler defined by us only processes requests other than/trans and/trans to the underlying layer for processing step 5. access the local running

     

     

    Run the following command: python server. py

    Access

    Access in the browser, view the effect, open the browser, enter: http: // localhost: 8000/

    Step 6. Upload the application

     

    Log on to Bluemix? You can use the cf push command to upload the application.

    Before you begin, you must:
    1. 1. Install the Cloud Foundry command line interface.

    2. Download the corresponding version based on your operating system. I use a Windows 7 64-bit operating system,
    3. The Binaries version does not need to be installed,Decompress the package directly to the Windows directory..
    4. Click the dashboard "pytrans (name of the application you created)" to start encoding. You can view your own commands, for example:
    5. 2. Connect to Bluemix.
    6. Open the Command Prompt window: Start, Run, enter "cmd", and press ENTER
    7. Run the cf api https://api.ng.bluemix.net, such:
    8. 3. log on to Bluemix.
    9. Note: replace it with the command corresponding to your own account!
    10.  cf login -u [email protected] -o [email protected] -s ivu4e

    4. When issuing the cf push command, the cf command line interface provides a working directory for building and running the Bluemix environment of the application using buildpack.

    1. Enter the cf push command with the application name in the application directory. In the Bluemix environment, the application name must be unique.
    2. The following "-m 512 m" modifies the application memory quota. this parameter is optional, for example:
    3. Note: Before executing cf push, switch the current directory of the command line to the application directory you just created. For example
      C: \ python \ pytrans \. Replace pytrans after cf push with the name of the application you created on Bluemix.
    4. Tip: when you use the cf push command, the cf command line interface copies all files and directories in the current directory to Bluemix. Make sure that the application directory contains only required files.
    5. The cf push command uploads the application and deploys it to Bluemix. For more information about cf push, see cf commands. For information about buildpack, see use the Community buildpack.

    6. If you have changed the application, you can run the cf push command again to upload the changes. The cf command line interface uses your previous options and your response to the prompt to update any running instances of the application through the new code segment. Tip: You can also upload or deploy applications from Bluemix DevOps Services. See use Web IDE in Node. js to develop Bluemix applications. Step 7. Perform a small test

      Go to the application page you just created through the dashboard, click Start code on the left side, and the top of the right side will show that your application is running. Http://pytrans.mybluemix.net/

      Click the link below to access the newly released application.

      Conclusion

      With IBM's Bluemix cloud platform, we can easily share our applications on the network;

      After a Web application is created, a second-level domain name is automatically obtained to access the application;

      The application running status in the Application overview can be used to conveniently view and manage the application running status;

      Here is a small example to show how to publish your application to the IBM Bluemix cloud platform,

      How to interact with the language translation service provided on the IBM cloud platform.

      If you have better applications or ideas, try sharing them with IBM's Bluemix cloud platform.

Related Article

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.