Exposing the REST APIs

Now that the code logic is in place, the remaining part is configuring and starting the HTTP server. In this application, the httpd driver from the cyclotron-aio package will be used. Its implementation is similar to the one that we performed in Chapter 3, Functional Programming with ReactiveX. This is also done with two code blocks:

  • One for the initialization of the server
  • One to return the responses when the audio encoding completes

Here is the initialization part:

    http_init = (
config
.flat_map(lambda i: Observable.from_([
httpd.Initialize(request_max_size=0),
httpd.AddRoute(
methods=['POST'],
path='/api/transcode/v1/flac/{key:[a-zA-Z0-9-._]*}',
id='flac_transcode',
),
httpd.StartServer(
host=i.server.http.host,
port=i.server.http.port),
]))
)

The httpd driver needs at least three items on its control sink observable to complete the initialization:

  • One with initialization parameters
  • One or several to configure the routes
  • A final one to start the server

The initialization message disables the maximum size accepted in the request payloads. This is necessary to accept requests with MP3 file content because the default limit is 2 MB, which is smaller than most existing audio files. Then, the unique route is declared. It accepts the HTTP POST method on a path that ends with a matching value named key. This value is the name to use when encoding the file. The id of the route is not really used in this case since there is only one route. Finally, the server is started with the host and port values provided in the configuration file.

The second code block is simpler:

    http_response = (
sources.encoder.response
.map(lambda i: httpd.Response(
data='ok'.encode('utf-8'),
context=i.id,
))
)

The http_response observable is a map of the encoding response to an HTTP response. An 'ok' text payload is put in the response, and the HTTP request context is retrieved from the encoding response id field. http_reponse and http_init can then be merged to create the observable provided to the httpd driver sink:

http = Observable.merge(http_init, http_response)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.93.132