Wednesday, 7 October 2020

Create simple python cors server at current folder and respond random JSON string to client

 1. create demoFolder, then create demoFolder/cgiServer.py


 cgiServer.py

#!/usr/bin/env python3


from http.server import CGIHTTPRequestHandler, HTTPServer


handler = CGIHTTPRequestHandler

handler.cgi_directories = ['/cgi-bin', '/htbin']  # this is the default

server = HTTPServer(('localhost', 8123), handler)

server.serve_forever()


2. In same directory create cgi-bin folder and create demoFolder/cgi-bin/test.py file

test.py file

#!/usr/bin/env python3


#-*- coding: utf-8 -*-

import json, uuid, random

import os, pickle


# create an empty dictionary

test_data = {}

# specify the number of keys (or 'documents') to create

# Threshold 4800000, 543MB

# total_documents = 4800000

# total_documents = 2400000

total_documents = 10

# print ("\n\nCreating " + str(total_documents) + " Elasticsearch documents:")

for key in range(total_documents):

    # give each pet document a UUID

    new_uuid = uuid.uuid4()


    # convert UUID to string

    new_uuid = str(new_uuid)


    # create a nest dictionary which represents the Elasticsearch document

    test_data[new_uuid] = {}


    # list for pet's name

    names = ['Bailey', 'Bear', 'Buddy', 'Charlie', 'Coco', 'Cosmo', 'Daisy', 'Lily', 'Lola', 'Maggy', 'Mango', 'Molly', 'Sadie', 'Sophie', 'Sunny', 'Tiger', 'Toby']

    # randomly select a name

    name = names[random.randint(0, len(names)-1)]


    # randomly select a dog or cat

    species = ['dog', 'cat'][random.randint(0, 1)]


    # randomly select the sex of the pet

    sex = ['male', 'female'][random.randint(0, 1)]


    # NOTE: The value for an Elasticsearch JSON document's field MUST

    # be a string, regardless of the actual data type

    age = str(random.randint(0, 10)) # randomly select the age of the pet


    # put all of the values into the dictionary

    test_data[new_uuid]['uuid'] = new_uuid

    test_data[new_uuid]['name'] = name

    test_data[new_uuid]['species'] = species

    test_data[new_uuid]['sex'] = sex

    test_data[new_uuid]['age'] = age


    # print the UUID and name of the JSON document

    # print (name + " has UUID: " + new_uuid)


# serialize the data

# with open('pets.pickle', 'wb') as handle:

#     pickle.dump(test_data, handle, protocol=pickle.HIGHEST_PROTOCOL)




# create an empty list for the JSON documents

document_list = []


# iterate over the keys and values of the nested dictionary

for key, val in test_data.items():

    # create a pet variable to represent the Elasticsearch document

    pet = test_data[key]


    # print a message about the pet

    # print ("Creating a JSON object for: " + pet['name'])


    '''

    Elasticsearch requires this 'index' field for every document. Each linebreak and "index" represents

    a single JSON document. Use '\n' for linebreaks:

    '''

    # json_string = '{"index":{}}\n' + json.dumps(pet) + '\n'

    # json_string = json.dumps(pet)

    # print ("New Elasticsearch document:" + json_string)


    # append the document string to the list

    # document_list += [json_string]

    document_list.append(pet)



print('Access-Control-Allow-Origin: *')

print('Access-Control-Allow-Headers: *')

print('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTION')

print('Content-type: application/json\n')

-----------------------start server by python3 cgiServer.py

/// Client side simple CORS ajax:

<!DOCTYPE html>

<html lang="en">


<head>

    <title>JavaScript - read JSON from URL</title>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>


<body>

    <div class="mypanel"></div>


    <script>

        var data = [];


        $.ajax({

            url: "http://localhost:8123/cgi-bin/test.py",

            type: "GET",

            crossDomain: true,

            success: function (response) {

                console.log('ajax success -> response -> ');

                console.log(typeof (response));

                console.log(response);

                data = data.concat(response);

                console.log('data concated -> ');

                console.log(data);


            },

            error: function (xhr, status) {

                console.log('ajax error -> xhr');

                console.log(xhr);

            }

        })


     

        // Promise.all([ajax1(), ajax1()]).then(() => {

        //     console.log('ajax return');

        //     console.log(ajax1());

        //     // all requests finished successfully

        // }).catch(() => {

        //     // all requests finished but one or more failed

        // })

        // function ajax1() {

        //     // NOTE:  This function must return the value

        //     //        from calling the $.ajax() method.

        //     return $.ajax({

        //         url: "http://localhost:8123/cgi-bin/test.py",

        //         type: "GET",

        //         crossDomain: true,

        //     });

        // }


    </script>


</body>


</html>

# print('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTION\n')

print(json.dumps(document_list))


No comments:

Post a Comment