[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python

適当すぎる占い.png

Fortune-telling site that is too suitable

Not long ago, I made a fortune-telling site that is too suitable.

I made some corrections after creating it, but the work time is actually about 1 hour.

Technology used

The technology used was Bottle, a Python web framework.

The database used SQLite3 and the CSS framework used Bulma.

Deploy to Heroku.

Creating a database

First of all, I created a database (SQLite3).

The database name is database.db.

set_fortune.py


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

import sqlite3
from contextlib import closing

dbname = 'database.db'

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()

    create_table = '''create table fortune (id int, text varchar(256))'''
    c.execute(create_table)

    insert_sql = 'insert into fortune (id, text) values (?,?)'
    fortune = [
        (1, 'Drinking mayonnaise in the shade may be disappointing.'),
        (2, 'Drinking coffee makes you breathe.'),
        (3, 'When you call out to the opposite sex with your eyes, 50%You can date with the probability of.'),
        (4, 'It's good to eat seafood noodles with Tabasco.'),
        (5, 'When you eat curry, your IQ will be 150.'),
        (6, 'There are good things to do when you try to get cigarette smoke out of your nose.'),
        (7, 'Even if you backflip in the middle of the road, it will be ignored.'),
        (8, 'I get nosebleeds when I eat chocolate bar.'),
        (9, 'Twist the water faucet and run until it overflows.'),
        (10, 'I'm tired of thinking about proper fortune-telling.'),
    ]
    c.executemany(insert_sql, fortune)
    conn.commit()

    select_sql = 'select * from fortune'
    for row in c.execute(select_sql):
        print(row)

I'm creating a table called fortune and creating id and text columns.

After that, I inserted 10 data.

As a method of inserting data later, you can insert it as follows.

$sqlite3 database.db
sqlite> insert into fortune values(11, 'I want to get good with Qiita');

Source code

Let's look at the source code.

index.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="index, follow">
    <meta name="application-name" content="Appropriate fortune-telling">
    <meta name="description" content="Do a proper fortune-telling.">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Sloppy fortune-telling</title>

    <link rel="stylesheet" href="../static/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
    <link href="https://fonts.googleapis.com/css?family=Gloria+Hallelujah|Kosugi&display=swap" rel="stylesheet">

  </head>
  <body>

  <section class="hero is-medium is-primary is-bold">
    <div class="hero-body">
      <div class="container">
        <h1 class="title">
          Sloppy fortune-telling
        </h1>
        <h2 class="subtitle">
Appropriate fortune-telling
        </h2>
      </div>
    </div>
  </section>

  <section class="section">
    <div class="container">

      <div class="field">
        <div class="control">
          <div class="select is-primary is-rounded is-medium">
            <select>
              <option>Aries</option>
              <option>Taurus</option>
              <option>Gemini</option>
              <option>Cancer</option>
              <option>Leo</option>
              <option>Virgo</option>
              <option>Libra</option>
              <option>Scorpio</option>
              <option>Sagittarius</option>
              <option>Capricorn</option>
              <option>Aquarius</option>
              <option>Pisces</option>
            </select>
          </div>
        </div>
      </div>

      <input class="input is-primary is-rounded is-medium" type="text" placeholder="Input your name">

      <div class="columns is-mobile is-centered">
        <button class="button is-primary is-rounded is-large" id="open">Fortune-telling!</button>
      </div>

      <div class="modal">
        <div class="modal-background"></div>
        <div class="modal-card">
          <header class="modal-card-head">
            <p class="modal-card-title">Today's fortune</p>
          </header>
          <section class="modal-card-body">
            {{result}}
          </section>
          <footer class="modal-card-foot">
            <button class="button" id="close">Close</button>
          </footer>
        </div>
      </div>

    </div>
  </section>

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

  <script>
    $(document).ready(function() {
      $("#open").on("click", function() {
        $("div.modal").addClass("is-active");
      })

      $("#close, div.modal-background").on("click", function() {
        $("div.modal").removeClass("is-active");
      })
    });
  </script>

  </body>
</html>

Bulma is read by CDN and the display is arranged.

When you press the button with id = open, Modal appears and the fortune-telling result is displayed.

For the sake of appearance, there is a constellation selection and name input field, but I will not use it for anything: D

app.py


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

from bottle import Bottle, template, static_file, url
import os
import random
import sqlite3

app = Bottle()

@app.route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

@app.route('/')
def index():

    con = sqlite3.connect('database.db')
    cur = con.cursor()

    num = str(random.randint(1,16))

    sql = 'select * from fortune where id = ' + num + ';'
    cur.execute(sql)

    for row in cur:
        result = row[1]

    con.close()

    return template('index', result=result)

@app.error(404)
def error404(error):
    return "Error 404. Try again later."

@app.error(500)
def error500(error):
    return "Error 500. Try again later."

# local test
app.run(host='localhost', port=8080, debug=True)

# heroku
# app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))

Connect to a database called databese.db and generate random numbers.

Since the fortune table has an id column, we are getting the fortune-telling result (text) where the generated random number and id match.

Deploy to Heroku

It was completed to some extent, so I deployed it to Heroku.

First of all, create the files needed for deployment.

$ pip3 freeze > requirements.txt        
$ echo web: python3 app.py > Procfile 

There are several ways to deploy to Heroku.

Personally, I find it easier to work with the GitHub repository.

After getting a Heroku account, select Create new app and set the App name and so on.

スクリーンショット 2020-02-13 15.02.13.png

After that, you can deploy by simply selecting GitHub from the "Deploy" Deployment method and linking it.

スクリーンショット 2020-02-13 15.01.22.png

Finally

I made a fortune-telling site that is too suitable.

If it improves, it will take shape to some extent. I think.

If you don't mind, please try the challenge for an hour! !!

reference

Sqlite @ mas9612 in Python

Links

Fortune-telling site that is too suitable: https://sloppy-fortune-telling.herokuapp.com/

GitHub: https://github.com/ShogoMurakami/sloppy-fortune-telling

Thanks, @shogo

Recommended Posts

[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
[2nd] I tried to make a certain authenticator-like tool with python
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a generator that generates a C # container class from CSV with Python
I want to make a game with Python
Python: I tried to make a flat / flat_map just right with a generator
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to make a simple mail sending application with tkinter of Python
I tried to draw a route map with Python
[Patent analysis] I tried to make a patent map with Python without spending money
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to automatically generate a password with Python3
I tried to make a real-time sound source separation mock with Python machine learning
[Mac] I want to make a simple HTTP server that runs CGI with Python
I tried to make various "dummy data" with Python faker
I tried to make a stopwatch using tkinter in python
I tried to make GUI tic-tac-toe with Python and Tkinter
[Python] I tried to make an application that calculates salary according to working hours with tkinter
I want to make a voice changer using Python and SPTK with reference to a famous site
I tried to make a system that fetches only deleted tweets
I tried to make a regular expression of "amount" using Python
[Python] I tried to implement stable sorting, so make a note
I tried to make a regular expression of "time" using Python
I tried to create a list of prime numbers with python
I tried to make a regular expression of "date" using Python
I tried to find out if ReDoS is possible with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I tried to make a strange quote for Jojo with LSTM
I tried to make an image similarity function with Python + OpenCV
I tried to make a mechanism of exclusive control with Go
I tried a functional language with Python
I tried to make a Web API
I tried to make a site that makes it easy to see the update information of Azure
[Python] I tried to make a simple program that works on the command line using argparse.
A story that didn't work when I tried to log in with the Python requests module
I tried to make an original language "PPAP Script" that imaged PPAP (Pen Pineapple Appo Pen) with Python
I tried to implement deep learning that is not deep with only NumPy
I tried to communicate with a remote server by Socket communication with Python.
I tried to implement a blockchain that actually works with about 170 lines
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I tried to make a calculator with Tkinter so I will write it
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
[AWS] [GCP] I tried to make cloud services easy to use with Python
I tried to develop a Formatter that outputs Python logs in JSON
I tried to discriminate a 6-digit number with a number discrimination application made with python
[Outlook] I tried to automatically create a daily report email with Python
I tried to build a Mac Python development environment with pythonz + direnv
I tried to make a skill that Alexa will return as cold
[Zaif] I tried to make it easy to trade virtual currencies with Python
I tried to make a url shortening service serverless with AWS CDK
[Python] When I tried to make a decompression tool with a zip file I just knew, I was addicted to sys.exit ()
I tried to get CloudWatch data with Python
Try to make a "cryptanalysis" cipher with Python
I tried to output LLVM IR with Python
I tried to automate sushi making with python