Changes between Version 5 and Version 6 of comoUsarElApi


Ignore:
Timestamp:
Nov 6, 2015, 10:02:24 AM (8 years ago)
Author:
aaraujo
Comment:

Agregada sección de prueba desde python

Legend:

Unmodified
Added
Removed
Modified
  • comoUsarElApi

    v5 v6  
    147147{{{ruby multipart.rb}}}
    148148
     149
     150
     151
     152=== Prueba básica con Python ===
     153
     154[[Image(python.png, 220px)]]
     155
     156A continuación se muestra un código muy básico para ilustrar cómo se pueden consumir recursos de Murachí desde el lenguaje python. Para correr el script python se requiere instalar el framework [http://docs.python-requests.org/en/latest/ requests], [https://pypi.python.org/pypi/M2Crypto M2Crypto] y el framework web [http://www.tornadoweb.org/en/stable/ tornado].
     157
     158{{{
     159#!/usr/bin/env python
     160# -*- coding: utf-8 -*-
     161
     162import os, uuid
     163
     164from M2Crypto import X509
     165
     166
     167import tornado.httpserver
     168import tornado.ioloop
     169import tornado.options
     170import tornado.web
     171
     172import requests
     173from requests.auth import HTTPBasicAuth
     174
     175from tornado.options import define, options
     176
     177define("port", default=8888, help="run on the given port", type=int)
     178
     179__UPLOADS__ = "/tmp/"
     180
     181# mensaje hola mundo
     182class IndexHandler(tornado.web.RequestHandler):
     183        def get(self):
     184                greeting = self.get_argument('greeting', 'Hello')
     185                self.write(greeting + ', friendly user!\n')
     186
     187# para obtener la version del servicio web
     188class VersionHandler(tornado.web.RequestHandler):
     189        def get(self):         
     190                # verify=False para no verificar el certificado del servidor web
     191                # auth=() para la autenticacion basica de HTTP
     192                r = requests.get('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/version', verify=False, auth=('admin', 'admin'))
     193                #r = requests.get('https://192.168.12.125:8443/Murachi/0.1/archivos/version', verify=False, auth=('admin', 'admin'))
     194                self.write(r.text)
     195                #r.json()
     196                #self.write(r.raise_for_status())
     197               
     198
     199
     200# para subir un archivo
     201class UploadHandler(tornado.web.RequestHandler):
     202        def get(self):
     203                #files = {'file': open('/tmp/reports.txt', 'rb')}
     204                # subir un pdf
     205                files = {'file': open('/home/cenditel/desarrollo/murachi/convenioSUSCERTE-CENDITEL.pdf', 'rb')}
     206                r = requests.post('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/cargar', verify=False, auth=('admin', 'admin'), files=files)
     207                #r = requests.post('https://192.168.12.125:8443/Murachi/0.1/archivos/cargar', verify=False, auth=('admin', 'admin'), files=files)
     208                #self.write(r.text)
     209                r.json()
     210                fileId = r.json()['fileId']
     211                self.write(fileId)
     212                self.write('\n')
     213
     214                #verificar si el documento esta firmado
     215                #r2 = requests.get('https://192.168.12.125:8443/Murachi/0.1/archivos/'+fileId, verify=False, auth=('admin', 'admin'), files=files)
     216                r2 = requests.get('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/'+fileId, verify=False, auth=('admin', 'admin'), files=files)
     217                self.write(r2.text)
     218               
     219# para obtener estadisticas basicas
     220class StatisticsHandler(tornado.web.RequestHandler):
     221        def get(self):
     222                r = requests.get('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/estadisticas', verify=False, auth=('admin', 'admin'))
     223                self.write(r.text)
     224               
     225
     226               
     227               
     228
     229# manejador principal
     230class MainHandler(tornado.web.RequestHandler):
     231        def get(self):
     232                self.write("""
     233                        <form name="input" action="/loadfile" method="post" enctype="multipart/form-data" >
     234                        archivo: <input type="file" name="fileToUpload"><br>
     235                        <input type="submit" value="Enviar"/>
     236                        </form>
     237                        """)
     238        def write_error(self, status_code, **kwargs):
     239                self.write("Gosh darnit, user! You caused a %d error." % status_code)
     240
     241
     242
     243class LoadHandler(tornado.web.RequestHandler):
     244        def post(self):
     245                #print self.request.arguments
     246                #self.write(self.request.arguments)
     247                #self.write("hola")
     248                #archivo = self.get_argument("file",'')
     249
     250                fileinfo = self.request.files['fileToUpload'][0]
     251                fname = fileinfo['filename']
     252                self.write(fname+'\n')
     253                extn = os.path.splitext(fname)[1]
     254                cname = str(uuid.uuid4()) + extn
     255                fh = open(__UPLOADS__ +cname, 'w')
     256                fh.write(fileinfo['body'])
     257                self.write('archivo subido: '+cname+'\n')
     258                #self.finish(cname + " is uploaded! Check %s folder" %__UPLOADS__)
     259
     260                mypage = u"""Hola mundo"""
     261                self.write(mypage)
     262
     263
     264if __name__ == "__main__":
     265        tornado.options.parse_command_line()
     266        #app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
     267        app = tornado.web.Application(handlers=[(r"/", MainHandler),
     268                                                (r"/index", IndexHandler),
     269                                                (r"/version", VersionHandler),
     270                                                (r"/upload", UploadHandler),
     271                                                (r"/estadisticas", StatisticsHandler),
     272                                                (r"/loadfile", LoadHandler)
     273        #                                       (r"/loadCertificate", LoadCertificateHandler)
     274                                                ])
     275       
     276        http_server = tornado.httpserver.HTTPServer(app, ssl_options={"certfile": "server.crt", "keyfile": "server.key"})
     277        http_server.listen(options.port)
     278        tornado.ioloop.IOLoop.instance().start()
     279}}}
     280
     281
     282
     283