可以理解assert断言语句为raise-if-not,是Python中定

2019-08-31 作者:编程   |   浏览(182)

python在线编写翻译器的总结原理及简便达成代码,python编写翻译器

笔者们先来看一下成效(简单的写了三个):

图片 1

图片 2

图片 3

规律:将post央求的代码数据写入了服务器的一个文本,然后用服务器的python编写翻译器施行回来结果

金玉锦绣代码:

#flaskrun.py 
# -*- coding: utf-8 -*- 
# __author__="ZJL"  
from flask import Flask 
from flask import request 
from flask import Response 
import 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('hello world!!!') 

@app.route('/run', methods=['POST']) 
def run(): 
  if request.method == 'POST' and request.form['code']: 
    code = request.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_headers(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(400) 
def page_not_found(error): 
  content = json.dumps({"error_code": "400"}) 
  resp = Response_headers(content) 
  return resp 

@app.errorhandler(405) 
def page_not_found(error): 
  content = json.dumps({"error_code": "405"}) 
  resp = Response_headers(content) 
  return resp 

@app.errorhandler(410) 
def page_not_found(error): 
  content = json.dumps({"error_code": "410"}) 
  resp = Response_headers(content) 
  return resp 

@app.errorhandler(500) 
def page_not_found(error): 
  content = json.dumps({"error_code": "500"}) 
  resp = Response_headers(content) 
  return resp 

if __name__ == '__main__': 
  app.run(debug=True) 

#zxby.py 
# -*- coding: utf-8 -*- 
# __author__="ZJL" 
import os, sys, subprocess, tempfile, time  
# 创建临时文件夹,返回临时文件夹路径 
TempFile = tempfile.mkdtemp(suffix='_test', prefix='python_') 
# 文件名 
FileNum = int(time.time() * 1000) 
# python编译器位置 
EXEC = sys.executable 

# 获取python版本 
def get_version(): 
  v = sys.version_info 
  version = "python %s.%s" % (v.major, v.minor) 
  return version 

# 获得py文件名 
def get_pyname(): 
  global FileNum 
  return 'test_%d' % FileNum 

# 接收代码写入文件 
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 

# 编码 
def decode(s): 
  try: 
    return s.decode('utf-8') 
  except UnicodeDecodeError: 
    return s.decode('gbk') 

  # 主执行函数  

def main(code): 
  r = dict() 
  r["version"] = get_version() 
  pyname = get_pyname() 
  fpath = write_file(pyname, code) 
  try: 
    # subprocess.check_output 是 父进程等待子进程完成,返回子进程向标准输出的输出结果 
    # stderr是标准输出的类型 
    outdata = decode(subprocess.check_output([EXEC, fpath], stderr=subprocess.STDOUT, timeout=5)) 
  except subprocess.CalledProcessError as e: 
    # e.output是错误信息标准输出 
    # 错误返回的数据 
    r["code"] = 'Error' 
    r["output"] = decode(e.output) 
    return r 
  else: 
    # 成功返回的数据 
    r['output'] = outdata 
    r["code"] = "Success" 
    return r 
  finally: 
    # 删除文件(其实不用删除临时文件会自动删除) 
    try: 
      os.remove(fpath) 
    except Exception as e: 
      exit(1) 

if __name__ == '__main__': 
  code = "print(11);print(22)" 
  print(main(code)) 

运行app.run()方法,通过post提交代码,就ok了。大家得以对输出结过做越来越的拍卖,作者那只是为驾驭一下原理,就没继续了。

以上正是本文的全体内容,希望对大家的学习抱有支持,也意在我们多多扶助帮客之家。

我们先来看一下意义(轻便的写了叁个): 原理:将post央浼的代码数据写入了服务...

Python模块WSGI使用详解,pythonwsgi使用详解

WSGI(Web Server Gateway Interface):Web服务网关接口,是Python中定义的服务器程序和应用程序之间的接口。

Web程序支付中,一般分为服务器程序和应用程序。服务器程序担当对socket服务的数码举办李包裹装和整理,而应用程序则承担对Web伏乞实行逻辑管理。

Web应用本质上也是一个socket服务器,顾客的浏览器便是叁个socket客商端。

我们先用socket编制程序落成贰个简练的Web服务器:

import socket 

def handle_request(client): 
  buf = client.recv(1024) 
  print(buf) 
  msg = "HTTP/1.1 200 OKrnrn" #HTTP头信息 
  client.send(('%s' % msg).encode()) 
  msg = "Hello, World!" 
  client.send(('%s' % msg).encode()) 

def main(): 
  ip_port = ("localhost", 8000) 
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
  sock.bind(ip_port) 
  sock.listen(5) 

  while True: 
    conn, addr = sock.accept() 
    handle_request(conn) 
    conn.close() 

if __name__ == "__main__": 
  main() 

上述代码中,main()函数就是服务器函数,handle_request()正是应用程序。
下边大家再用python的wsgiref模块来贯彻跟上述代码同样的Web服务器:

from wsgiref.simple_server import make_server 

def handle_request(env, res): 
  res("200 OK",[("Content-Type","text/html")]) 
  body = "<h1>Hello World!</h1>" 
  return [body.encode("utf-8")] 

if __name__ == "__main__": 
  httpd = make_server("",8000,handle_request) 
  print("Serving http on port 80000") 
  httpd.serve_forever() 

地方两份代码完结的机能是一律的,调用wsgiref模块则鲜明节省了代码量,是整整程序更为从简。
wsgiref模块封装了socket服务端的代码,只留下二个调用的接口,省去了技师的分神,技术员能够将精力放在Web央浼的逻辑管理中。

以上述的代码为例,详细看一下wsgiref模块的源码中部分重要的地点:

if __name__ == "__main__": 
  httpd = make_server("",8000,handle_request) 
  print("Serving http on port 80000") 
  httpd.serve_forever() 

1、整个程序的进口为make_server()函数:

def make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler): 
  """Create a new WSGI server listening on `host` and `port` for `app`""" 
  server = server_class((host, port), handler_class) #默认创建一个WSGIServer类 
  server.set_app(app) #将应用程序,即逻辑处理函数传给类 
  return server 

2、make_server()函数暗许生成八个WSGIServer类:

class WSGIServer(HTTPServer):
class HTTPServer(socketserver.TCPServer):
class TCPServer(BaseServer):

WSGIServer,HTTPServer七个类未有起始化函数,调用父类的开始化函数,TCPServer类的__init__()函数扩充了BaseServer

类的__init__()函数:

#BaseServer类的__init__()函数: 
def __init__(self, server_address, RequestHandlerClass): 
  """Constructor. May be extended, do not override.""" 
  self.server_address = server_address 
  self.RequestHandlerClass = RequestHandlerClass 
  self.__is_shut_down = threading.Event() 
  self.__shutdown_request = False 

#TCPServer类的__init__()函数: 
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): 
  """Constructor. May be extended, do not override.""" 
  BaseServer.__init__(self, server_address, RequestHandlerClass) 
  self.socket = socket.socket(self.address_family,self.socket_type) 
    if bind_and_activate: 
      try: 
        self.server_bind() 
        self.server_activate() 
      except: 
        self.server_close() 
        raise 

TCPServer类的初阶化函数还调用了server_bind(self),server_bind(self)三个函数:

def server_bind(self): 
  """Called by constructor to bind the socket.May be overridden.""" 
  if self.allow_reuse_address: 
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
  self.socket.bind(self.server_address) 
  self.server_address = self.socket.getsockname()  
def self.server_activate(self): 
  """Called by constructor to activate the server.May be overridden.""" 
  self.socket.listen(self.request_queue_size)  

能够观望server.bind()函数调用了socket.bind()函数,而server_activate()调用了socket.listen()函数:

3、server.set_app(app),此处传入Web央求的拍卖逻辑:

def set_app(self,application): 
  self.application = application 

4、httpd.serve_forever()函数调用BaseServer类的_handle_request_noblock()函数管理多路要求:

def _handle_request_noblock(self): 
  try: 
    request, client_address = self.get_request() #get_request()调用了socket.accept()函数 
  except OSError: 
    return 
  if self.verify_request(request, client_address): 
    try: 
      self.process_request(request, client_address) 
    except: 
      self.handle_error(request, client_address) 
      self.shutdown_request(request) 
  else: 
    self.shutdown_request(request) 

def process_request(self, request, client_address): 
  self.finish_request(request, client_address)   
  self.shutdown_request(request)#shutdown_request()调用socket.close()关闭socket 

def finish_request(self, request, client_address): 
  """Finish one request by instantiating RequestHandlerClass.""" 
  self.RequestHandlerClass(request, client_address, self) 

5、process_request()函数调用了finish_request()函数,简单介绍调用了make_server函数的暗许参数WSGIRequestHandler类:

class WSGIRequestHandler(BaseHTTPRequestHandler):
class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
class StreamRequestHandler(BaseRequestHandler):

#调用BaseRequestHandler类的初始化函数: 
def __init__(self, request, client_address, server): 
  self.request = request 
  self.client_address = client_address 
  self.server = server 
  self.setup() 
  try: 
    self.handle() 
  finally: 
    self.finish() 

6、初叶化函数调用之后调用WSGIRequestHandler类的handle()函数获取server的逻辑管理函数:

def handle(self): 
  """Handle a single HTTP request""" 
  try: 
    handler = ServerHandler(self.rfile, stdout, self.get_stderr(), self.get_environ()) 
    handler.request_handler = self   # backpointer for logging 
    handler.run(self.server.get_app()) #此处调用server的逻辑处理函数 
  finally: 
    stdout.detach() 

7、BaseHandler类的handler.run()函数试行逻辑管理:

def run(self, application): 
   try: 
    self.setup_environ() 
    self.result = application(self.environ, self.start_response) 
    self.finish_response() 
  except: 
    try: 
      self.handle_error() 
    except: 
      self.close() 
      raise  # ...and let the actual server figure it out. 

self.environ:三个分包全部HTTP央浼音信的dict对象
self.start_response:二个出殡和埋葬HTTP响应的函数。

在application函数中,调用:

res("200 OK",[("Content-Type","text/html")]) 

那般就发送了HTTP响应的头音信

8、BaseHandler类的setup_environ()函数获取HTTP哀告的头新闻:

def setup_environ(self): 
  """Set up the environment for one request""" 
  env = self.environ = self.os_environ.copy() 

os_environ= read_environ() 

read_environ()函数: 

def read_environ(): 
  """Read environment, fixing HTTP variables""" 
  enc = sys.getfilesystemencoding() 
  esc = 'surrogateescape' 
  try: 
    ''.encode('utf-8', esc) 
  except LookupError: 
    esc = 'replace' 
  environ = {} 

  # Take the basic environment from native-unicode os.environ. Attempt to 
  # fix up the variables that come from the HTTP request to compensate for 
  # the bytes->unicode decoding step that will already have taken place. 
  for k, v in os.environ.items(): 
    if _needs_transcode(k): 

      # On win32, the os.environ is natively Unicode. Different servers 
      # decode the request bytes using different encodings. 
      if sys.platform == 'win32': 
        software = os.environ.get('SERVER_SOFTWARE', '').lower() 

        # On IIS, the HTTP request will be decoded as UTF-8 as long 
        # as the input is a valid UTF-8 sequence. Otherwise it is 
        # decoded using the system code page (mbcs), with no way to 
        # detect this has happened. Because UTF-8 is the more likely 
        # encoding, and mbcs is inherently unreliable (an mbcs string 
        # that happens to be valid UTF-8 will not be decoded as mbcs) 
        # always recreate the original bytes as UTF-8. 
        if software.startswith('microsoft-iis/'): 
          v = v.encode('utf-8').decode('iso-8859-1') 

        # Apache mod_cgi writes bytes-as-unicode (as if ISO-8859-1) direct 
        # to the Unicode environ. No modification needed. 
        elif software.startswith('apache/'): 
          pass 

        # Python 3's http.server.CGIHTTPRequestHandler decodes 
        # using the urllib.unquote default of UTF-8, amongst other 
        # issues. 
        elif ( 
          software.startswith('simplehttp/') 
          and 'python/3' in software 
        ): 
          v = v.encode('utf-8').decode('iso-8859-1') 

        # For other servers, guess that they have written bytes to 
        # the environ using stdio byte-oriented interfaces, ending up 
        # with the system code page. 
        else: 
          v = v.encode(enc, 'replace').decode('iso-8859-1') 

      # Recover bytes from unicode environ, using surrogate escapes 
      # where available (Python 3.1 ). 
      else: 
        v = v.encode(enc, esc).decode('iso-8859-1') 

    environ[k] = v 
  return environ 

9、BaseHandler类的start_response()函数:

def start_response(self, status, headers,exc_info=None): 
  """'start_response()' callable as specified by PEP 3333""" 
  if exc_info: 
    try: 
      if self.headers_sent: 
        # Re-raise original exception if headers sent 
        raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) 
    finally: 
      exc_info = None    # avoid dangling circular ref 
  elif self.headers is not None: 
    raise AssertionError("Headers already set!") 

  self.status = status 
  self.headers = self.headers_class(headers) 
  status = self._convert_string_type(status, "Status") 
  assert len(status)>=4,"Status must be at least 4 characters" 
  assert status[:3].isdigit(), "Status message must begin w/3-digit code" 
  assert status[3]==" ", "Status message must have a space after code" 

  if __debug__: 
    for name, val in headers: 
      name = self._convert_string_type(name, "Header name") 
      val = self._convert_string_type(val, "Header value")   
  return self.write 

如上正是本文的整体内容,希望对大家的读书抱有支持,也冀望大家多多援助帮客之家。

WSGI(Web Server Gateway Interface):Web服务网关接口,是Python中定义的服务器程序和应用程序之间的接...

Python断言assert的用法代码分析,pythonassert

在开辟一个前后相继时候,与其让它运维时崩溃,比不上在它现身谬误条件时就夭折(再次来到错误)。那时候断言assert 就显得十分管用。

python assert断言是宣称布尔值必需为真正决断,若是爆发特别就认证表达式为假。

能够精晓assert断言语句为raise-if-not,用来测量检验表示式,其重返值为假,就会接触相当。

assert的语法格式:

assert expression

它的等价语句为:

if not expression:
  raise AssertionError

这段代码用来检验数据类型的断言,因为 a_str 是 str 类型,所以以为它是 int 类型肯定会抓住错误。

>>> a_str = 'this is a string'
>>> type(a_str)
<type 'str'>
>>> assert type(a_str)== str
>>> assert type(a_str)== int

Traceback (most recent call last):
 File "<pyshell#41>", line 1, in <module>
  assert type(a_str)== int
AssertionError

numpy使用技能之数组过滤实例代码,numpy使用本领

本文钻探的显假诺numpy使用技术之数组过滤的连带内容,具体如下。

当使用布尔数组b作为下标存取数组x中的成分时,将访谈数组x中持有在数组b中对应下标为True的要素。使用布尔数组作为下标得到的数组不和原始数组分享数据空间,注意这种形式只对应于布尔数组(array),不能够选取布尔列表(list)。

>>> x = np.arange(5,0,-1)
>>> x
array([5, 4, 3, 2, 1])
>>> x[np.array([True, False, True, False, False])]
>>> # 下标为True的取出来,布尔数组中下标为0,2的元素为True,因此获取x中下标为0,2的元素
array([5, 3])
>>> x[[True, False, True, False, False]]#Error,这不是我们想要的结果
>>> # 如果是布尔列表,则把True当作1, False当作0,按照整数序列方式获取x中的元素
array([4, 5, 4, 5, 5])
>>> x[np.array([True, False, True, True])]
>>> # 布尔数组的长度不够时,不够的部分都当作False
array([5, 3, 2])
>>> x[np.array([True, False, True, True])] = -1, -2, -3#只修改下标为True的元素
>>> # 布尔数组下标也可以用来修改元素
>>> x
array([-1, 4, -2, -3, 1])

在意:布尔数组一般不是手工发生的,常常大家选取一条布尔表明式来赢得,如:

>>> x = np.random.rand(10) # 产生一个长度为10,元素值为0-1的随机数的数组
>>> x
array([ 0.72223939, 0.921226 , 0.7770805 , 0.2055047 , 0.17567449,
    0.95799412, 0.12015178, 0.7627083 , 0.43260184, 0.91379859])
>>> x>0.5
>>> # 数组x中的每个元素和0.5进行大小比较,得到一个布尔数组,True表示x中对应的值大于0.5
array([ True, True, True, False, False, True, False, True, False, True], dtype=bool)
>>> x[x>0.5]# x>0.5是一个布尔数组
>>> # 使用x>0.5返回的布尔数组收集x中的元素,因此得到的结果是x中所有大于0.5的元素的数组
array([ 0.72223939, 0.921226 , 0.7770805 , 0.95799412, 0.7627083 ,
    0.91379859])

本文由小鱼儿玄机30码发布于编程,转载请注明出处:可以理解assert断言语句为raise-if-not,是Python中定

关键词: 小鱼儿玄机30码