Blogiprogramm

Allikas: Lambda

Serveris vaja teha sql tabel blog andmebaasi blog.sql, kus väljad content,date,time:

create table blog(
   id integer primary key, 
   content varchar(2000),
   date text,
   time text
);

Flask peab järgnevas olema installeeritud. Läptoppi või serverisse samasse kataloogi, kus blog.sql, pane programm blog.py ja käivita kui python blog.py:

from flask import Flask, request
import sqlite3
import json 
app = Flask(__name__)

@app.route('/blog', methods=['POST', 'GET'])
def sum():
  c=request.args.get("c",'')
  conn = sqlite3.connect('blog.sql')
  cur = conn.cursor()
  if c:
    sql = """ 
      insert into blog(content,date,time) 
      values ('"""+c+"""',date('now'),time('now'));
      """ 
    cur.execute(sql)
  sql2="""select id,content,date,time from blog"""
  cur.execute(sql2)
  res=cur.fetchall()
  cur.close()
  conn.commit()
  conn.close()
  return json.dumps(res)

app.run(debug=True, port=5000, host='0.0.0.0')

ja sealsamas /static kataloogi alla pane html:

<form>
  please enter blog text:<br>
  <input type='text' id='c'><p> 
  <input type='button' onclick='send()' 
    value='send'>
</form>
<div id="ans"></div>

<script>
function send() {
  var c,url;
  c=document.getElementById('c').value;  
  url="/blog?c="+c;
  fetch(url, {
    method: "get"
  }).then(r=>r.json()).then(handleresult);
}
function handleresult(r) {
  console.log(r);
  s="<p>";
  console.log("r length ",r.length);
  for(var i=0; i<r.length; i++) {
    console.log(i,r[i]);
    var elem=r[i];    
    line="<b>"+JSON.stringify(elem[1])+"</b> ";
    line=line+elem[2]+" "+elem[3];
    s=s+line+"<p>";

  }
  document.getElementById('ans').innerHTML=s;
}
</script>

ja siis ava brauserist kui http://serverinimi:5000/static/blog.html