Пример #1
0
    def do_GET(self):
        """
        """
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)
        print(parsed_qs)
        if parsed_path.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'''<!DOCTYPE html>
            <html>
              <head>
                <title> cowsay </title>
              </head>
              <body>
               <header>
                 <nav>
                   <ul>
                     <li><a href="/cowsay">cowsay</a></li>
                   </ul>
                 </nav>
               <header>
               <main>
                 <p>This project is designed to test specific routes and return status messages accordingly</p>
               </main>
              </body>
            </html>''')
            return

        elif parsed_path.path == '/cow':
            try:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                parsed_message = parsed_qs['msg'][0]
                cheese = cow.Moose(eyes='dead')
                msg = cheese.milk(parsed_message)
                self.wfile.write(msg.encode())
                return

            except KeyError:
                self.send_response(400)
                self.end_headers()
                cheese = cow.Moose()
                msg = cheese.milk('400 Bad Request')
                self.wfile.write(msg.encode())

        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Cow not found. Moo.')

        self.send_response(404)
        self.end_headers()
Пример #2
0
    def do_GET(self):
        """handles route for GET requests"""
        parsed_path = urlparse(self.path)
        # print('parsed path {} => '.format(parsed_path))
        parsed_qs = parse_qs(parsed_path.query)

        if parsed_path.path == '/':
            self.send_response(200)
            self.end_headers()
            """https://docs.python.org/3/tutorial/inputoutput.html"""
            with open('index.html') as f:
                fdata = f.read()
                self.wfile.write(fdata.encode('utf8'))
            return

        elif parsed_path.path == '/cowsay':
            """handles endpoint cowsay"""
            cheese = cow.Moose(thoughts=True)
            msg = cheese.milk("I have a hole in my head")

            self.send_response(200)
            self.end_headers()
            self.wfile.write(msg.encode('utf8'))
            return

        elif parsed_path.path == '/cow':
            """handles endpoint cow and parses msg=xxxx from url"""
            cheese = cow.Moose(thoughts=True)

            try:
                msg = json.loads(parsed_qs['msg'][0])
            except json.decoder.JSONDecodeError:
                msg = parsed_qs['msg'][0]
            except KeyError:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'Bad Request | 400')
                return

            self.send_response(200)
            self.end_headers()
            self.wfile.write(cheese.milk(msg).encode('utf8'))
            return

        else:
            """404"""
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not Found')
Пример #3
0
    def add_good():
        if not USER.get('login', None):
            print(colored("Unregistered", "red"))
            input()
            return
        print(cow.Moose().milk("Order"))
        print()
        name = input("Enter good name: > ")
        description = input("Enter good description: > ")
        cost = int(input("Enter good cost: > "))
        visible = int(input("Input y if good is visible: > ") == 'y')
        if not re.match(r'^[a-zA-Z0-9 _]+$', name):
            print("Name is invalid")
            input()
            return
        if not re.match(r'^[a-zA-Z0-9 _=]+$', description):
            print("Description is invalid")
            input()
            return

        with open("items.txt", "a") as w:
            fcntl.flock(w, fcntl.LOCK_EX)
            w.write("{}|{}|{}|{}\n".format(name, cost, visible, description))
            fcntl.flock(w, fcntl.LOCK_UN)
        print(colored("Success", "green"))
        input()
        return
Пример #4
0
    def do_POST(self):
        """post returns json of message"""
        parsed_path = urlparse(self.path)
        # parsed_qs = parse_qs(parsed_path.query)

        if parsed_path.path == '/cow':

            try:
                content_length = int(self.headers['Content-Length'])
                body = json.loads(
                    self.rfile.read(content_length).decode('utf8'))

            except KeyError:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'Bad Request | 400')
                return

        cheese = cow.Moose(thoughts=True)
        msg = cheese.milk(body['msg'])

        self.send_response(200)
        self.end_headers()
        self.wfile.write(json.dumps({'content': msg}).encode('utf8'))
        return
Пример #5
0
 def do_POST(self):
     """post request"""
     parsed_path = urlparse(self.path)
     # parsed_qs = parse_qs(parsed_path.query)
     if parsed_path.path == '/cow':
         """check if post request hase correct route"""
         try:
             content_length = int(self.headers['Content-Length'])
             body = json.loads(
                 self.rfile.read(content_length).decode('utf8'))
         except KeyError:
             self.send_response(400)
             self.end_headers()
             self.wfile.write(b'something is broken')
             return
         cheese = cow.Moose(tongue=True)
         msg = cheese.milk(body['msg'])
         self.send_response(200)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
         self.wfile.write(json.dumps({'content': msg}).encode('utf8'))
         return
     else:
         self.send_response(404)
         self.end_headers()
         self.wfile.write(b'Not Found')
Пример #6
0
def cowpyify(msg):
    """Pass a string through cowpy.

    input: msg (str): string to modify
    return: (str) new string wrapped in cowpy text
    """
    cheese = cow.Moose()
    return cheese.milk(msg)
Пример #7
0
 def register():
     print(cow.Moose().milk("Registration"))
     print()
     login = input("Enter Login: > ")
     password = input("Enter Password: > ")
     USER['login'] = login
     USER['password'] = password
     USER['money'] = 100
     print("Created user {} with password {}.\nPress any key.".format(
         login, '*' * len(password)))
     input()
Пример #8
0
def lambda_handler(event, context):
    moose = cow.Moose()
    msg = moose.milk("hello")
    # msg   = moose.milk("helz")
    print "HELLO\n"
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "text/plain"
        },
        "body": str(msg) + "\n",
    }
Пример #9
0
 def show_goods():
     print(cow.Moose().milk("Goods"))
     with open("items.txt") as r:
         print('\n'.join([
             colored(good[0], 'red') + ["", " — " + good[3]][int(good[2])] +
             colored(" ({})".format(good[1]), 'green') for good in filter(
                 lambda x: x,
                 map(lambda x: x.split('|'),
                     filter(lambda x: x,
                            r.read().split('\n'))))
         ]))
     input()
Пример #10
0
 def order_goods():
     print(cow.Moose().milk("Order"))
     print()
     good = input("Enter good name: > ")
     load_goods()
     if good not in GOODS:
         print("No such good")
         input()
         return
     print("Here is your payment token: {}".format(
         str(binascii.hexlify(encode_aes(GOODS[good])))[2:-1]))
     input()
Пример #11
0
def cowsayMessage(message):

    ###################################################
    #  Print a messsage usig COW library              #
    ###################################################

    # Create a Cow
    my_cow = cow.Moose()
    # Get a cowsay message by milking the cow
    msg = my_cow.milk(message)
    # do something with the message
    print(msg)

    return True
Пример #12
0
def moothedata(data, key=None):
    """Return an amusing picture containing an item from a dict.

    Parameters
    ----------
    data: mapping
        A mapping, such as a raster dataset's ``meta`` or ``profile``
        property.
    key:
        A key of the ``data`` mapping.
    """
    if not key:
        key = choice(list(data.keys()))
        logger.debug("Using randomly chosen key: %s", key)
    msg = cow.Moose().milk("{0}: {1}".format(key.capitalize(), data[key]))
    return msg
Пример #13
0
 def auth():
     print(cow.Moose().milk("Authentication"))
     print()
     login = input("Enter Login: > ")
     if USER.get('login', None) != login:
         print("Invalid login")
         input()
         return
     password = input("Enter Password: > ")
     if USER.get('password', None) != password:
         print("Invalid password")
         input()
         return
     USER['is_auth'] = True
     print("OK. Press any key.")
     input()
Пример #14
0
    def do_GET(self):
        """
        This method will allow you to send HTTP Requests
        """
        cheese = cow.Moose()
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        # set a status code
        # set any headers
        # set any body data on the response
        # end headers

        if parsed_path.path == '/':
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write(httpcow.encode())
            return

        elif parsed_path.path == '/cow':
            try:
                if len(parsed_qs['msg'][0]) < 1:
                    self.send_response(400)
                    self.send_header('Content-Type', 'text/html')
                    self.end_headers()
                    self.wfile.write(b'400 Bad Request')
                    return
                msg = cheese.milk(parsed_qs['msg'][0])
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(
                    f'''<html><body>{msg}</body></html>'''.encode())
                return
            except KeyError:
                self.send_response(400)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(b'400 Bad Request')
                return

        self.send_response(404)
        self.end_headers()
Пример #15
0
    def do_GET(self):
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        # import pdb; pdb.set_trace()

        if parsed_path.path == '/':
            self.send_response(200)
            self.end_headers()

            self.wfile.write(return_html_string())
            return

        elif parsed_path.path == '/cowsay':
            self.send_response(200)
            self.end_headers()

            self.wfile.write(b'Helpful instructions about this application')
            return

        elif parsed_path.path == '/cow':
            try:
                # import pdb; pdb.set_trace()
                msg = parsed_qs['msg'][0]
                print(msg)
            except (KeyError, json.decoder.JSONDecodeError):
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'You did a bad thing')
                return

            cheese = cow.Moose(thoughts=True)
            message = cheese.milk(msg)

            self.send_response(200)
            self.end_headers()
            self.wfile.write(message.encode('utf8'))
            return

        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not Found')
Пример #16
0
 def search_goods():
     print(cow.Moose().milk("Search goods"))
     print()
     good = input("Enter good search string: > ")
     with open("items.txt") as r:
         content = r.read()
         results = re.findall(
             re.compile("^(.*?" + good + ".*?)\|.*$", re.MULTILINE),
             content)
         results2 = re.findall(
             re.compile("^.*?\|\d+\|\d+\|(.*?" + good + ".*?)$",
                        re.MULTILINE), content)
         if len(results):
             print('\n'.join([colored(res, 'red') for res in results]))
         elif len(results2):
             print('\n'.join([colored(res, 'red') for res in results2]))
         else:
             print("No such good")
     input()
     return
Пример #17
0
    def do_POST(self):
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        if parsed_path.path == '/cow':
            try:
                msg = parsed_qs['msg'][0]
                cheese = cow.Moose(thoughts=True)
                message = cheese.milk(msg)
                post_dict = {}
                post_dict['content'] = message
                self.send_response(200)
                self.end_headers()
                self.wfile.write(json.dumps(post_dict).encode('utf8'))
                return
            except (KeyError, json.decoder.JSONDecodeError):
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'You did a bad thing')
                return
Пример #18
0
 def pay_check():
     if not USER.get('login', None):
         print(colored("Unregistered", "red"))
         input()
         return
     load_goods()
     print(cow.Moose().milk("Order"))
     print()
     token = input("Enter payment token: > ")
     _, good = decode_aes(token)
     name, cost, visible = unpad(good.decode())[1:-1].split(",")
     if int(cost) > int(USER['money']):
         print(colored("Not enough money", "red"))
     else:
         print(
             colored(
                 "Successfully bought {} ({})".format(
                     name, GOODS[name]["description"]), "green"))
         USER['money'] -= int(cost)
     input()
     return
Пример #19
0
    def do_POST(self):
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        if parsed_path.path == '/cow':
            try:
                msg = parsed_qs['msg'][0]
            except (KeyError, json.decoder.JSONDecodeError) as err:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'You did a bad thing')
                print(parsed_qs, err)
                return

            self.send_response(200)
            self.end_headers()
            content = {'content': cow.Moose().milk(msg)}
            self.wfile.write(json.dumps(content).encode('utf8'))
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not Found')
Пример #20
0
    def do_POST(self):
        """
        This is the method that will allow us to post
        """
        cheese = cow.Moose()
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        # set a status code
        # set any headers
        # set any body data on the response
        # end headers

        if parsed_path.path == '/cow':
            try:
                if len(parsed_qs['msg'][0]) < 1:
                    self.send_response(400)
                    self.send_header('Content-Type', 'text/html')
                    self.end_headers()
                    self.wfile.write(b'400 Bad Request')
                    return
                msg = cheese.milk(parsed_qs['msg'][0])
                return_json = f'{{"content": "{msg}"}}'
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(return_json.encode())
                return
            except KeyError:
                self.send_response(400)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(b'400 Bad Request')
                return

        self.send_response(404)
        self.end_headers()
Пример #21
0
#!/usr/bin/env python
# encoding: utf-8

from cowpy import cow

# Create a Cow
cheese = cow.Moose()

# Get a cowsay message by milking the cow
msg = cheese.milk("My witty mesage")

# do something with the message
print(msg)

# Create a Cow with a thought bubble
cheese = cow.Moose(thoughts=True)
msg = cheese.milk("My witty mesage, with thought")
print(msg)

# Create a Cow with a tongue
cheese = cow.Moose(tongue=True)
msg = cheese.milk("My witty mesage, with tongue")
print(msg)

# Create a Cow with dead eyes
cheese = cow.Moose(eyes='dead')
msg = cheese.milk("my witty mesage, i'm dead")
print(msg)

# Get a cow by name
cow_cls = cow.get_cow('moose')
Пример #22
0
#!/usr/bin/env python

from cowpy import cow

# creating a cow with a thought bubble
betty = cow.Moose(thoughts=True)
msg = betty.milk("I love Python!")

print(msg)
Пример #23
0
def test_server_post_sends_back_json():
    response = requests.post('http://127.0.0.1:3000/cow?msg="Hello world"')
    assert response.status_code == 200
    content = {'content': cow.Moose().milk('"Hello world"')}
    assert response.text == json.dumps(content)
Пример #24
0
def test_server_sends_qs_back():
    response = requests.get('http://127.0.0.1:3000/cow?msg="Hello world"')
    assert response.status_code == 200
    assert response.text == cow.Moose().milk('"Hello world"')
Пример #25
0
    with open("file/berhasil.txt") as f:
        with open("file/hasil_total.txt", "a") as f1:
            for line in f:
                f1.write(line)

    # reset file
    open('file/buffer.txt', 'w').close()
    open('file/berhasil.txt', 'w').close()


limit_per_sender = 3
session_iteration = 40

from cowpy import cow

cheese = cow.Moose(tongue=True)
msg = cheese.milk("Selamat Mengirim Email")
print(msg)

for i in range(session_iteration):
    with open('file/email_sender.txt') as f:
        for line in f:
            line = line.split(',')
            from_address = line[0]
            password = line[1]
            send_gmail_session(from_address, password, limit_per_sender)
    print(
        ' =======================>>> Rollingan ke %i <<<======================='
        % (i))
    time.sleep(200)
Пример #26
0
def cowpass():
    cheese = cow.Moose()
    print(cheese.milk(_xkcdpass_string()))
Пример #27
0
install cowpy
from cowpy import cow

# Create a Cow
cheese = cow.Moose()
msg = cheese.milk("Hello Analytics Vidhya")
print(msg)
Пример #28
0
def trace_endpoint():
    cheese = cow.Moose(thoughts=True)
    message = cheese.milk("My witty mesage, for Posting Traces")
    print(message)
    return message
Пример #29
0
    def do_GET(self):
        parsed_path = urlparse(self.path)
        parsed_qs = parse_qs(parsed_path.query)

        # import pdb; pdb.set_trace()

        if parsed_path.path == '/':
            self.send_response(200)
            self.end_headers()

            self.wfile.write(b'''
<!DOCTYPE html>
<html>
<head>
    <title> cowsay </title>
</head>
<body>
    <header>
        <nav>
        <ul>
            <li><a href="/cowsay">cowsay</a></li>
        </ul>
        </nav>
    <header>
    <main>
        <!-- project description -->
    </main>
</body>
</html>
            ''')
            return
        elif parsed_path.path == '/cowsay':
            self.send_response(200)
            self.end_headers()

            self.wfile.write(cow.Moose().milk(
                'Use /cow?msg="text" to see your message').encode('utf8'))
            return
        elif parsed_path.path == '/cow':
            try:
                msg = parsed_qs['msg'][0]
            except (KeyError, json.decoder.JSONDecodeError):
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'You did a bad thing')
                return

            self.send_response(200)
            self.end_headers()
            self.wfile.write(cow.Moose().milk(msg).encode('utf8'))
            return
        # elif parsed_path.path == '/test':
        #     try:
        #         cat = json.loads(parsed_qs['category'][0])
        #     except KeyError:
        #         self.send_response(400)
        #         self.end_headers()
        #         self.wfile.write(b'You did a bad thing')
        #         return

        #     self.send_response(200)
        #     self.end_headers()
        #     self.wfile.write(b'we did the thing with the qs')
        #     return

        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Not Found')
Пример #30
0
DINO_ALIAS.keys()





# ------------------------------------------------
#
#   cowpy
#       https://github.com/jeffbuttars/cowpy
#
# ------------------------------------------------

from cowpy import cow

print(cow.Moose().milk("wahahahha"))
print(cow.Moose(eyes='dead', tongue=True).milk("wahahahha"))
print(cow.Moose(eyes='dead', tongue=True, thoughts=True).milk("wahahahha"))

print(cow.milk_random_cow("agadkjfasldkj"))


# list options
print(cow.cow_options())
print(cow.eye_options())





# ------------------------------------------------