Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Flask Blog App #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions flask_blog/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 HARIKRUSHN KANANI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions flask_blog/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn app:main
54 changes: 54 additions & 0 deletions flask_blog/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# flask_blog
A Simple Blog App to Add a Blog.

# How to Use
# 1) Package Requirements :)
first import required package of python by following command on command prompt:
```
pip install flask
pip install flask-mail
pip install Flask-SQLAlchemy
```
# 2) Software Requirements :)
install Xampp or Wampp sever on your PC
then Create a Database Called codingthunder and create two tables posts and contacts
inside posts table we have
```
sno, title, tagline, slug, content, img_file, date --> This Attributes
```

and inside comments table we have
```
sno, name, phone_num, msg, date, email --> This Attributes
```

# 3) Download the Source Code :)

clone this repository by following Command.
```
git clone https://github.com/harikanani/flask_blog.git
```
goto the file location
```
cd flask_blog
```
and then open Command Prompt there and type following command
```
python main.py
```

# Output Screens
# HomePage
![](./screen/img1.png)

# HomePage With Blogs
![](./screen/img2.png)
![](./screen/img3.png)

# AboutPage
![](./screen/img4.png)
![](./screen/img5.png)

# Contact Us Page
![](./screen/img6.png)
![](./screen/img7.png)
20 changes: 20 additions & 0 deletions flask_blog/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"params" : {
"local_server" : "True",
"local_uri" : "mysql+pymysql://root:@localhost/codingthunder",
"prod_uri" : "mysql+pymysql://root:@localhost/codingthunder",
"fb_url" : "https://www.facebook.com/harikrishan.kanani/",
"tw_url" : "https://www.twitter.com/Harikrushn9",
"gh_url" : "https://www.github.com/harikanani/",
"blog_name" : "Coding Thunder",
"tagline" : "Haven for Programmers.",
"gmail-user" : "[email protected]",
"gmail-password" : "123abc0.",
"about_text" : "Hii, My name is Harry. I'm Learning Flask and I'm Good Boy.",
"no_of_posts" : 3,
"login_image" : "login.svg",
"admin_user": "admin",
"admin_password": "pass",
"upload_location" : "D:\\Programming Projects\\FlaskProjects\\Flask_Blog\\static\\img"
}
}
66 changes: 66 additions & 0 deletions flask_blog/contacts.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Sep 01, 2020 at 07:48 AM
-- Server version: 10.4.10-MariaDB
-- PHP Version: 7.4.0

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `codingthunder`
--

-- --------------------------------------------------------

--
-- Table structure for table `contacts`
--

DROP TABLE IF EXISTS `contacts`;
CREATE TABLE IF NOT EXISTS `contacts` (
`sno` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`phone_num` varchar(50) NOT NULL,
`msg` text NOT NULL,
`date` datetime DEFAULT current_timestamp(),
`email` varchar(50) NOT NULL,
PRIMARY KEY (`sno`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `contacts`
--

INSERT INTO `contacts` (`sno`, `name`, `phone_num`, `msg`, `date`, `email`) VALUES
(1, 'first', '9999999999', 'first Message Testing...!!!', '2020-08-31 11:13:58', '[email protected]'),
(2, 'harry', '123456789', 'hello Message..!!!', '2020-08-31 13:15:43', '[email protected]'),
(3, 'harry', '123456789', 'message me.!!!!', '2020-08-31 13:21:12', '[email protected]'),
(4, 'abhi', '8987685612', 'I\'m Abhi. I\'ve Seen your Blog and implement it but i\'m getting some errors.\r\nPlease send me your Contact information so i can share my errors or contact me on : \r\n+918987685612\r\n\r\nThank you !\r\ni hope you\'ll reply me as soon as you read this.\r\n\r\nYour BlogViewer,\r\nAbhi Goyani', '2020-08-31 13:26:47', '[email protected]'),
(5, 'abhi', '8987685612', 'I\'m Abhi. I\'ve Seen your Blog and implement it but i\'m getting some errors.\r\nPlease send me your Contact information so i can share my errors or contact me on :\r\n+918987685612\r\n\r\nThank you !\r\ni hope you\'ll reply me as soon as you read this.\r\n\r\nYour BlogViewer,\r\nAbhi Goyani', '2020-08-31 13:30:23', '[email protected]'),
(6, 'abhi', '8987685612', 'I\'m Abhi. I\'ve Seen your Blog and implement it but i\'m getting some errors.\r\nPlease send me your Contact information so i can share my errors or contact me on : \r\n+918987685612\r\n\r\nThank you !\r\ni hope you\'ll reply me as soon as you read this.\r\n\r\nYour BlogViewer,\r\nAbhi Goyani', '2020-08-31 13:30:54', '[email protected]'),
(7, 'harry', '123456789', 'message me.!!!!', '2020-08-31 13:31:13', '[email protected]'),
(8, 'harry', '1234567889', '12345', '2020-08-31 13:31:57', '[email protected]'),
(9, 'harry', '1234567889', '12345', '2020-08-31 13:33:00', '[email protected]'),
(10, 'testing', '1237761209', 'testing is mail sent or not?', '2020-08-31 13:35:20', '[email protected]'),
(11, 'testing', '1234567889', 'testing mail sent or not?\r\n', '2020-08-31 13:36:07', '[email protected]'),
(12, 'harry', '1234567889', '1234', '2020-08-31 13:36:33', '[email protected]'),
(13, 'harry', '1234567889', '1234', '2020-08-31 13:36:51', '[email protected]'),
(14, 'DK', '6865458796', 'encesdnec hiwena uuwe bwce ubudb', '2020-08-31 13:38:48', '[email protected]'),
(15, 'testing', '1237761209', 'tesing message for sending mail to my original account', '2020-08-31 13:40:11', '[email protected]');
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
180 changes: 180 additions & 0 deletions flask_blog/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
from flask import Flask, render_template, request, session, redirect, flash
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from datetime import datetime
import json
import os
import math
from werkzeug.utils import secure_filename

with open('config.json', 'r') as c:
params = json.load(c)["params"]

local_server = params['local_server']
app = Flask(__name__)
app.secret_key = 'super-secret-key'
app.config['UPLOAD_FOLDER'] = params['upload_location']
app.config.update(
MAIL_SERVER = 'smtp.gmail.com',
MAIL_PORT = '465',
MAIL_USE_SSL = 'True',
MAIL_USERNAME = params['gmail-user'],
MAIL_PASSWORD = params['gmail-password'],
)
mail = Mail(app)
if local_server == True:
app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']
else:
app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']

db = SQLAlchemy(app)


class Contacts(db.Model):
sno = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=False, nullable=False)
phone_num = db.Column(db.String(12), nullable=False)
msg = db.Column(db.String(120), nullable=False)
date = db.Column(db.String(12), nullable=True)
email = db.Column(db.String(20), nullable=False)

class Posts(db.Model):
sno = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), unique=False, nullable=False)
slug = db.Column(db.String(30), nullable=False)
content = db.Column(db.String(120), nullable=False)
date = db.Column(db.String(12), nullable=True)
img_file = db.Column(db.String(40), nullable=False)
tagline = db.Column(db.String(40), nullable=False)


@app.route("/")
# @app.route("/home")
def Home():

posts = Posts.query.filter_by().all()
last = math.ceil(len(posts)/int(params['no_of_posts']))
# [0:params['no_of_posts']]

page = request.args.get('page')
if not str(page).isnumeric() :
page = 1
page = int(page)

posts = posts[(page-1)*int(params['no_of_posts']): (page-1)*int(params['no_of_posts']) + int(params['no_of_posts'])]
# Pagination Logic
# First - Previous = # && Next = page+1
if page==1:
prev = "#"
Next = "/?page=" + str(page + 1)
elif page==last:
prev = "/?page=" + str(page - 1)
Next = "#"
else:
prev = "/?page=" + str(page - 1)
Next = "/?page=" + str(page + 1)

return render_template('index.html', params=params, posts=posts, prev=prev, Next=Next)

@app.route("/about")
def about():
return render_template('about.html', params=params)

@app.route("/contact", methods = ['GET', 'POST'])
def contact():
if (request.method == 'POST'):
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
message= request.form.get('message')

entry = Contacts(name=name, phone_num=phone, msg=message, email=email, date=datetime.now())
db.session.add(entry)
db.session.commit()
mail.send_message('New Message From ' + name,
sender=email,
recipients= [params['gmail-user']],
body = "Phone Number is : " + phone + "\n\nMessage is : " + "\n" + message
)
flash('Thanks for submitting your details. We\'ll get back soon.', "success")
return render_template('contact.html', params=params)

@app.route("/edit/<string:sno>", methods = ['GET', 'POST'])
def edit(sno):
if ('user' in session and session['user'] == params['admin_user']):
if request.method == 'POST':
box_title = request.form.get('title')
tline = request.form.get('tline')
slug = request.form.get('slug')
content = request.form.get('content')
img_file = request.form.get('img_file')
date = datetime.now()

if sno=='0':
post = Posts(title=box_title, slug=slug, content=content, tagline=tline, img_file=img_file, date=date)
db.session.add(post)
db.session.commit()
else:
post = Posts.query.filter_by(sno=sno).first()
post.title = box_title
post.slug = slug
post.content = content
post.tagline = tline
post.img_file = img_file
post.date = date
db.session.commit()
return redirect('/edit/'+sno)
post = Posts.query.filter_by(sno=sno).first()
return render_template('edit.html', params=params, post=post, sno=sno)


@app.route("/post/<string:post_slug>", methods=['GET'])
def post_route(post_slug):
post = Posts.query.filter_by(slug=post_slug).first()
return render_template('post.html', params=params, post=post)


@app.route("/delete/<string:sno>")
def delete():
pass

@app.route("/logout")
def logout():
session.pop('user')
return redirect('/dashboard')


@app.route("/uploader", methods = ['GET', 'POST'])
def uploader():
if 'user' in session and session['user'] == params['admin_user']:
if request.method == "POST":
f = request.files['file1']
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
return "Uploaded Successfully"


# @app.route("/dashbord", methods = ['GET', 'POST'])
# def logout():
# posts=Posts.query.all()
# return render_template('dashbord.html', params=params, posts=posts)

@app.route("/dashboard", methods = ['GET', 'POST'])
def dashbord():

if 'user' in session and session['user'] == params['admin_user']:
posts=Posts.query.all()
return render_template('dashboard.html', params=params, posts=posts)

if request.method == 'POST' :
username = request.form.get('uname')
userpass = request.form.get('pass')

if (username == params['admin_user'] and userpass == params['admin_password']):
session['user'] = username
posts=Posts.query.all()
return render_template('dashboard.html', params=params, posts=posts)

return render_template('login.html', params=params)

# if __name__ == '__main__':
app.run(debug=True)
Loading