{"id":1318,"date":"2015-12-22T23:27:39","date_gmt":"2015-12-22T23:27:39","guid":{"rendered":"http:\/\/islascruz.org\/blog\/?p=1318"},"modified":"2019-08-20T17:37:49","modified_gmt":"2019-08-20T22:37:49","slug":"python-simple-http-server-on-python","status":"publish","type":"post","link":"https:\/\/islascruz.org\/blog\/2015\/12\/22\/python-simple-http-server-on-python\/","title":{"rendered":"Python: Simple HTTP Server on python."},"content":{"rendered":"<p>(Repost from old blog)<\/p>\n<p><a title=\"Python Programming Language\" href=\"http:\/\/www.python.org\/\" target=\"_blank\" rel=\"noopener\">Python<\/a> have several modules that help you to achieve your goals. This week, on my spare time that is getting every day more scarce I spend time figuring out how to create a Python Web Server, I was planing to use it over an application that I&#8217;m developing on ICT Consulting. At the end I didn&#8217;t use it because I didn&#8217;t want a &#8220;passive&#8221; communication, but probably I will use this code on the <a title=\"Interleave CRM CTT, the CRM we use at ICT Consulting\" href=\"http:\/\/www.crm-ctt.com\/\" target=\"_blank\" rel=\"noopener\">CRM<\/a> Desktop application that we use here.<\/p>\n<p>Anyway, this code may be helpful for you too. I found that creating a small web server is really simple, It starts getting bigger as you add functions to that web server, but the basis is quite simple.<\/p>\n<pre>import os\nimport cgi\nimport sys\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\n \nclass customHTTPServer(BaseHTTPRequestHandler):\n        def do_GET(self):\n                self.send_response(200)\n                self.send_header('Content-type', 'text\/html')\n                self.end_headers()\n                self.wfile.write('&lt;HTML&gt;&lt;body&gt;Get!&lt;\/body&gt;&lt;\/HTML&gt;')\n                return \n                \n        def do_POST(self):\n                global rootnode\n                ctype,pdict = cgi.parse_header(self.headers.getheader('Content-type'))\n                if ctype == 'multipart\/form-data':\n                        query = cgi.parse_multipart(self.rfile, pdict)\n                self.send_response(301)\n                self.end_headers()\n                self.wfile.write('Post!')\n        \n                \ndef main():\n        try:\n                server = HTTPServer(('',8080),customHTTPServer)\n                print 'server started at port 8080'\n                server.serve_forever()\n        except KeyboardInterrupt:\n                server.socket.close() \n \nif __name__=='__main__':\n        main()<\/pre>\n<p>There are two main methods in our small server: do_GET and do_POST, you can figure out what this methods do. Get is quite simple, Post is used to send data to the server, as an example, the file uploading. This is done via POST and many times using &#8220;multipat\/form-data&#8221; as the content type. The Post method here handles that.<\/p>\n<p>Now that you have a custom server, how can you check it?, well, to check GET you can call it from the web browser. For the POST stuff, you can create a simple web form and using your web browser as &#8220;action&#8221; on it. However, this code can help you:<\/p>\n<pre class=\"lang:python\">import urllib2\nimport urllib\nimport time\nimport httplib, mimetypes\n \nHOST = '127.0.0.1'\nPORT = '8080' \n \ndef post_multipart(host, port, selector, fields, files):\n        \"\"\"\n        Post fields and files to an http host as multipart\/form-data.\n        fields is a sequence of (name, value) elements for regular form fields.\n        files is a sequence of (name, filename, value) elements for data to be uploaded as files\n        Return the server's response page.\n        \"\"\"\n        content_type, body = encode_multipart_formdata(fields, files)\n        h = httplib.HTTP(host, port)\n        h.putrequest('POST', '\/cgi-bin\/query')\n        h.putheader('content-type', content_type)\n        h.putheader('content-length', str(len(body)))\n        h.endheaders()\n        h.send(body)\n        #errcode, errmsg, headers = h.getreply()\n        h.getreply()\n        return h.file.read() \n \ndef encode_multipart_formdata(fields, files):\n        \"\"\"\n        fields is a sequence of (name, value) elements for regular form fields.\n        files is a sequence of (name, filename, value) elements for data to be uploaded as files\n        Return (content_type, body) ready for httplib.HTTP instance\n        \"\"\"\n        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_\n\nDid you like this?, don't forget to share!\n\n        CRLF = '\\r\\n'\n        L = []\n        if fields:\n                for (key, value) in fields:\n                        L.append('--' + BOUNDARY)\n                        L.append('Content-Disposition: form-data; name=\"%s\"' % key)\n                        L.append('')\n                        L.append(value)\n        if files:\n                for (key, filename, value) in files:\n                        L.append('--' + BOUNDARY)\n                        L.append('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (key, filename))\n                        L.append('Content-Type: %s' % get_content_type(filename))\n                        L.append('')\n                        L.append(value)\n        L.append('--' + BOUNDARY + '--')\n        L.append('')\n        body = CRLF.join(L)\n        content_type = 'multipart\/form-data; boundary=%s' % BOUNDARY\n        return content_type, body \n \ndef get_content_type(filename):\n        return mimetypes.guess_type(filename)[0] or 'application\/octet-stream' \n \ndef test():\n        print  post_multipart(HOST, PORT, 'markuz',\n                                        ( ('username','markuz'),  ('another_field','another value')),\n                                        (('query','query','Query'), ),\n                                   ) \n \nif __name__ == '__main__':      \n     test()\n\n<\/pre>\n<p>Did you like this?, don&#8217;t forget to share!<\/p>\n<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_1318\" class=\"pvc_stats all  \" data-element-id=\"1318\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img loading=\"lazy\" decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/islascruz.org\/blog\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n","protected":false},"excerpt":{"rendered":"<p>(Repost from old blog) Python have several modules that help you to achieve your goals. This week, on my spare time that is getting every day more scarce I spend time figuring out how to create a Python Web Server, I was planing to use it over an application that I&#8217;m developing on ICT Consulting. [&hellip;]<\/p>\n<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_1318\" class=\"pvc_stats all  \" data-element-id=\"1318\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img loading=\"lazy\" decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/islascruz.org\/blog\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n","protected":false},"author":1,"featured_media":5814,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[257,14,15,239],"tags":[318,258,259],"class_list":["post-1318","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldblog","category-programming","category-python","category-tips-and-tricks","tag-featured","tag-old-blog","tag-repost"],"a3_pvc":{"activated":true,"total_views":21146,"today_views":0},"brizy_media":[],"_links":{"self":[{"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/posts\/1318","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/comments?post=1318"}],"version-history":[{"count":12,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/posts\/1318\/revisions"}],"predecessor-version":[{"id":5813,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/posts\/1318\/revisions\/5813"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/media\/5814"}],"wp:attachment":[{"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/media?parent=1318"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/categories?post=1318"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/islascruz.org\/blog\/wp-json\/wp\/v2\/tags?post=1318"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}