forked from apiaryio/language-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.html
More file actions
26 lines (25 loc) · 1.11 KB
/
python.html
File metadata and controls
26 lines (25 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<section name="python" class="python">
<p class="ioDesc">Request</p>
<pre class="incoming"><code class="language-python">from urllib2 import Request, urlopen
<% if @contentType is "application/json": %>
from json import dumps
<% else if @contentType is "application/x-www-form-urlencoded": %>
from urllib import urlencode
<% end %>
<% if @contentType is "application/x-www-form-urlencoded" and @body: %>
values = urlencode(<%= @body %>)
<% else if @contentType is "application/json" and @body: %>
values = dumps(<%= @body %>)
<% else if @method isnt 'GET' and @body: %>
values = <%= @helpers.escape @body %>
<% end %>
<% if @helpers.isNotEmpty @headers: %>
headers = {<%= ("#{@helpers.escape header}: #{@helpers.escape value}" for header,value of @headers).join(", ") %>}
<% end %>
request = Request("<%= @apiUrl %><%= @url %>"<% if @method isnt 'GET' and @body : %>, data=values<% end %><% if @helpers.isNotEmpty @headers: %>, headers=headers<% end %>)
<% if @method not in ['GET', 'POST'] : %>
request.get_method = lambda: '<%= @method %>'
<% end %>
response_body = urlopen(request).read()
print response_body</code></pre>
</section>