The simple principle and super simple implementation of Python's online compiler __python

Source: Internet
Author: User

Nothing's going to happen today. The Python compiler for the beginner tutorial found it interesting to figure out what it was, so I entered the following code:

Import Sys,os
print (sys.version_info) print (sys.executable) print (sys.path[0) print
(os.listdir (Sys.path[0]
) With open ("/usercode/file.py") as E:
	print (E.read ())
The result is this:

I would speculate that it was writing the code data for the POST request to a file on the server and then executing the return result with the server's Python compiler


So I simply realized a

Directory structure:

Onlineexec

|----zxby.py

|----App

|----flaskrun.py


zxby.py Code implementation:

#-*-coding:utf-8-*-#__author__ = "Zjl" Import os,sys,subprocess,tempfile,time # Create temporary folder, return temporary folder path Tempfile = Tempfil E.mkdtemp (suffix= ' _test ', prefix= ' python_ ') # filename filenum = Int (time.time () *1000) # python compiler position EXEC = sys.executable #获取  Python version def get_version (): v = sys.version_info Version = "python%s.%s"% (V.major,v.minor) return version #
    Get the PY filename def get_pyname (): Global FileNum return ' test_%d '% FileNum # receive code to write to file Def write_file (Pyname, code):
    Fpath = Os.path.join (tempfile, '%s.py '% pyname) with open (Fpath, ' W ', encoding= ' Utf-8 ') as F:f.write (code) Print (' File path:%s '% Fpath) return Fpath # coded def decode (s): Try:return s.decode (' utf-8 ') exc EPT unicodedecodeerror:return s.decode (' GBK ') # Main executive function def main (code): R = dict () r["Version" = Get_vers Ion () Pyname = Get_pyname () Fpath = Write_file (pyname, code) Try: # Subprocess.check_output is the parent process waits for the child process
     Completes, returns the output of the child process to the standard output   # stderr is the standard output type Outdata = Decode (Subprocess.check_output (EXEC, Fpath), stderr=subprocess. STDOUT, timeout=5)) except subprocess. Calledprocesserror as E: # e.output is error message standard output # error returned data r[' Code ' = ' ERROR ' r[' output '] = d
        Ecode (E.output) return R else: # successfully returned data r[' output ' = outdata r[' code ']= ' Success ' return R finally: # Delete file (in fact, delete temporary files will be deleted automatically) Try:os.remove (Fpath) except except
 Ion as E:exit (1) # if __name__ = = ' __main__ ': # code = "" "Print (" Hello ")" "# Print (Main (code))


flaskrun.py Code implementation:

#-*-coding:utf-8-*-#__author__ = "ZJL" from flask import flask to flask Import request from flask import Response im Port JSON import Zxby app = Flask (__name__) def response_headers (content): resp = Response (content) resp.headers [' access-control-allow-origin '] = ' * ' Return resp @app. Route ('/") def Hello_world (): Return response_headers (' Hel

Lo World!!! ') @app. Route ('/run ', methods=[' post]) def run (): if Request.method = = ' POST ' and request.form[' code ']: Code = RE


quest.form[' Code '] Print (code) Jsondata = Zxby.main (code) return Response_headers (str (jsondata)) @app. ErrorHandler (403) def page_not_found (error): Content = Json.dumps ({"Error_code": "403"}) resp = Response_hea DERs (content) return resp @app. ErrorHandler (404) def page_not_found (error): Content = Json.dumps ({"Error_code": "  404 "}" resp = response_headers (content) return resp @app. ErrorHandler (=) def page_not_found (Error): Content = JSON.DUmps ({"Error_code": "The"}) Resp = response_headers (content) return resp @app. ErrorHandler (405) def Page_not_foun D (Error): Content = Json.dumps ({"Error_code": "405"}) Resp = response_headers (content) return resp @app. Error Handler (410) def page_not_found (error): Content = Json.dumps ({"Error_code": "410"}) resp = Response_headers (conten
    T) return resp @app. ErrorHandler def page_not_found (error): Content = Json.dumps ({"Error_code": "500"})
 RESP = response_headers (content) Return RESP if __name__ = = ' __main__ ': App.run (debug=true)

To open the Postman test:

Correct code test:


Error code test:




That's roughly what it is.

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.