Posts By vishavjeet (23)

Get the Test/Production credentials MID, merchant key for PAYTM Payment Gateway

Step1: Login for Paytm Dashboard using our paytm credentioals

           URL: https://dashboard.paytm.com/next/activate


Step2:  Click on Test Mode enabled

       Hint: find text like below

                   "Test Mode enabled

                    You can try out the Dashboard in Test Mode"


Step3:  Generate Test API Keys 

           Hint: Click on "Generate now" button


Note: If you don't want to create PAYTM merchant account for payment gateway then you can skip and  use test credential  which are given below


MID: DIY12386817555501617

Merchant Key: bKMfNxPPf_QdZppa

WEBSITE: DIYtestingweb

Channel id: WEB

Industry type id: Retail


You can access our Merchant Panel for seeing your transaction history and performing other operations:

URL: https://pguat.paytm.com/PayTMSecured/app/auth/login

Username: DIYtesting

Password: Paytm@197


After successfully initiating a transaction request, you can login to the test Wallet below & complete sample transactions :

Mobile Number : 7777777777

Password : Paytm12345

OTP : 489871


NOTE :

Refer the link below to download the plugin and utility kit as per your requirement.

http://paywithpaytm.com/developer/

API documentation –

http://paywithpaytm.com/developer/paytm_api_doc/

Mobile SDK documentation –

http://paywithpaytm.com/developer/paytm_sdk_doc/

Redirection: Once the transaction is completed you will be redirected to :

http://paywithpaytm.com/developer/

You can perform a STATUS QUERY to know the status of your transactions:

https://pguat.paytm.com/oltp/HANDLER_INTERNAL/TXNSTATUS?JsonData={“MID”:”xxxxxxxxxxxxxxxxxxx”,”ORDERID”:”xxxxxxxxxxxx”}

Reference::-http://paywithpaytm.com/developer/discussion/topic/sandbox-test-credentials-for-testing-paytm-solutions/


If Any Query ping on signal

How can export data from database using python script?

import csv

import mysql.connector

db = mysql.connector.connect( host="", user="", password="", database="")

cursor= db.cursor()

cursor.execute("SELECT p.product_title, p.product_sku, ms.size_title, ps.product_quantity QTY FROM products p INNER JOIN product_sizes ps ON p.product_id=ps.product_id INNER JOIN master_sizes ms ON ps.size_id=ms.size_id ORDER BY p.product_id DESC")

result = cursor.fetchall()

with open('product_inventory.csv', 'w', newline='') as file:

    writer = csv.writer(file)

    writer.writerow(["Product Title", "Product Sku", "Size", "QTY"])

   for x in result:

       writer.writerow(list(x))

OS Module In python

import os

print(os)

#<module 'os' from 'C:\\Users\\1131\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\os.py'>

print(os.path)

#<module 'ntpath' from 'C:\\Users\\1131\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\ntpath.py'>

print(os.name) # nt

#'posix', 'nt', 'java'

print(os.environ)


print(os.environ["HOME"])

# C:\Users\1131

print(os.chdir("D:/py_core_python")) #Change Directory

print(os.getcwd()) #D:\py_core_python

print(os.path.abspath("django")) #D:\py_core_python\nishu\django

print(os.path.dirname(os.path.abspath("django"))) #D:\py_core_python\nishu

print(os.path.dirname(os.path.dirname(os.path.abspath("django"))))

print("...")

print(__file__) # D:/py_core_python/_os_module.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

print(BASE_DIR)

print(os.path.join(BASE_DIR, "django"))

# os.fchdir(fd)

# os.getcwd()

# os.fchmod(fd, mode)

# os.open(path, flags, mode=0o777, *, dir_fd=None)

# import os

#

# # Build paths inside the project like this: os.path.join(BASE_DIR, ...)

# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Flask Setup and Basic

### Step1: Create virtualenv

>python -m virtualenv env

>virtualenv\scripts\activate

Create Virtual environment for ubuntu/linux machine and activate

>python -m venv env

>source env/bin/activate

### Step2: Creating Project

>mkdir demo_project

>cd demo_project

>

### Step3: Creating python file main.py


from flask import Flask

app = Flask(__name__)

@app.route("/")

def test():

return "Hello this is for testing and print in console!"

@app.route("/demo")

def harry():

return "this is second route url which in /demo"

app.run(debug=True)


### step5: Run server

>python main.py


##Tutorial2: Static and Templates folder

What is Static in flask?

This folder is public, client can access it. it may be images, css, javascript and other files.

These files can also be viewed using the www.website-url/static/filename address.

What is Templates in flask?

Templates folder is private, client can not access it. All the sensitive data is put in it.

Flask uses its template folder for storing the raw templates which can be filled through the python program.

Flask will look for templates in the templates folder.

So if your application is a module, this folder is next to that module,

if it’s a package it’s actually inside your package:

Case 1: a module:

/application.py

/templates

/index.html

Case 2: a module:

/application

/__init__.py

/templates

/index.html

Step1: Creating Static folder and templates

>mkdir static

>mkdir templates

What is render_template() function and where is use it?

render_template() function return a template(HTML page) through our python file.

Ex: render_template(‘html_file_name.html’, params={}) #as shown in the code below

return render_template('index.html', params={"title":"Home Page",

"keywords": "python, programming, numpy, pandas",

"description":"Python Tutorial for Beginners." },

"image_url": url_for("user_image", filename=user.image)

)

How can get Variable, images, css, js and include child html files in parent html?

Load Image

<img src="{{ url_for('static', filename='1.png') }}">

<img src="{{ url_for('static', filename='subfolder/2.png') }}">

<img src="/static/2.png">

Get python variable in html

<h1>Hi I am {{ variable_name }}!</h1>

<img src="{{ params.image_url }}">

<meta name="keywords" content="{{ params.keywords }}">

<meta name="Description" content="{{ params.description }}">

<title>{{ params.title }}</title>

For Loop In Template

{% for post in posts %}

#Slicing

{{post.content[0:101]}}...

{% endfor %}

How can set variable in Flask(Jinda) Template

{% set image_url = 'images/' + params.image_url %}

<img src="{{ url_for('static', filename=image_url) }}">

Inherit/include html files

{% include 'include/header.html' %}

{% include 'include/footer.html' %}

Load JS and CSS

<script src="/static/common/js/codemirror/lib/codemirror.js"></script>

<img src="{{ url_for('static', filename='js/jquery-3.5.1.min.js') }}">

<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">\

Variable Rules

You can add variable sections to a URL by marking sections with <variable_name>.

Your function then receives the <variable_name> as a keyword argument.

Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.

string (default): accepts any text without a slash

int :accepts positive integers

float: accepts positive floating point values

path: like string but also accepts slashes

uuid: accepts UUID strings

from markupsafe import escape

@app.route('/user/<username>')

def show_user_profile(username):

# show the user profile for that user

return 'User %s' % escape(username)

@app.route('/post/<int:post_id>')

def show_post(post_id):

# show the post with the given id, the id is an integer

return 'Post %d' % post_id

@app.route('/path/<path:subpath>')

def show_subpath(subpath):

# show the subpath after /path/

return 'Subpath %s' % escape(subpath)

Unique URLs / Redirection Behavio(Redirect with traling slash)

The following two rules differ in their use of a trailing slash.

#If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash.

@app.route('/projects/')

def projects():

return 'The project page'

@app.route('/about')

def about():

return 'The about page'

URL Building

To build a URL to a specific function, use the url_for() function.

It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule.

Unknown variable parts are appended to the URL as query parameters

test_request_context() method to try out url_for(). test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell.

from flask import url_for

with app.test_request_context():

print(url_for('test'))

print(url_for('projects'))

print(url_for('projects', next='/'))

print(url_for('user', username='John Doe'))

HTTP Methods:

Web applications use different HTTP methods when accessing URLs.

You should familiarize yourself with the HTTP methods as you work with Flask.

By default, a route only answers to GET requests.

You can use the methods argument of the route() decorator to handle different HTTP methods.

from flask import request

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

return do_the_login()

else:

return show_the_login_form()

The Request Object:

from flask import request

def log_the_user_in(username):

print(username)

return username

def valid_login(username, password):

print(username, password)

return True

@app.route('/user-login', methods=['POST', 'GET'])

def login():

error = None

if request.method == 'POST':

if valid_login(request.form['username'],

request.form['password']):

return log_the_user_in(request.form['username'])

else:

error = 'Invalid username/password'

# the code below is executed if the request method

# was GET or the credentials were invalid

return render_template('user-login.html', error=error)

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

File Uploads:

set the enctype="multipart/form-data" attribute on your HTML form,

otherwise the browser will not transmit your files at all.

Uploaded files are stored in memory or at a temporary location on the filesystem.

You can access those files by looking at the files attribute on the request object.

Each uploaded file is stored in that dictionary.

It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server.

Here is a simple example showing how that works:

from os.path import join, dirname, realpath

from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])

def upload_file():

if request.method == 'POST':

file = request.files['my-file']

filename = secure_filename(file.filename)

UPLOADS_PATH = join(dirname(realpath(__file__)), f'static/uploads/{filename}')

#file.save(UPLOADS_PATH, filename)

file.save(UPLOADS_PATH)

return render_template('file-upload.html' , message="File Uploaded Successfully.")

if request.method == 'GET':

return render_template('file-upload.html' , message="")

Cookies:

To access cookies you can use the cookies attribute.

To set cookies you can use the set_cookie method of response objects.

The cookies attribute of request objects is a dictionary with all the cookies the client transmits.

If you want to use sessions, do not use the cookies directly but instead

use the Sessions in Flask that add some security on top of cookies for you.

@app.route('/set-cookies')

def set_cookies():

username = request.cookies.get('username')

# use cookies.get(key) instead of cookies[key] to not get a

# KeyError if the cookie is missing.

render_template('cokkies.html', username=username)

#Storing cookies:

from flask import make_response

@app.route('/get-cookies')

def get_cookies():

resp = make_response(render_template('cokkies.html'))

resp.set_cookie('username', 'the username')

return resp

Redirects and Errors:

To redirect a user to another endpoint, use the redirect() function;

to abort a request early with an error code, use the abort() function:

from flask import abort, redirect, url_for

def this_is_never_executed():

return "This is never executed"

@app.route('/redirect')

def redirect():

return redirect(url_for('redirect-login'))

@app.route('/redirect-login')

def redirect_login():

abort(401)

this_is_never_executed()

Sessions:

In order to use sessions you have to set a secret key. Here is how sessions work:

from flask import Flask, session, redirect, url_for, request

from markupsafe import escape

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route('/')

def index():

if 'username' in session:

return 'Logged in as %s' % escape(session['username'])

return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

session['username'] = request.form['username']

return redirect(url_for('index'))

return '''

<form method="post">

<p><input type=text name=username>

<p><input type=submit value=Login>

</form>

'''

@app.route('/logout')

def logout():

# remove the username from the session if it's there

session.pop('username', None)

return redirect(url_for('index'))

# Logging

This might be caused by a user tampering with the data, or the client code failing.

Most of the time it’s okay to reply with 400 Bad Request in that situation,

but sometimes that won’t do and the code has to continue working.

app.logger.debug('A value for debugging')

app.logger.warning('A warning occurred (%d apples)', 42)

app.logger.error('An error occurred')

SQLAlchemy:

#pip install flask-sqlalchemy

from flask_sqlalchemy import SQLAlchemy

from datetime import datetime

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/test_db'

db = SQLAlchemy(app)

class Contacts(db.Model):

sno = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String(80), 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)

@app.route("/contact", methods = ['GET', 'POST'])

def contact():

if(request.method=='POST'):

'''Add entry to the database'''

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, date= datetime.now(),email = email )

db.session.add(entry)

db.session.commit()

return render_template('contact.html')

Admin DashBoard Access

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

def dashboard():

if 'user' in session AND session['user']==params['admin_user']:

// Access dashboard template

if request.method=='POST':

username= request.form.get('username')

password= request.form.get('password')

if username==params['admin_user'] AND password==params['password']:

session['user']==username

// Access dashboard template

// Access Login Template

else:

// access Login template

@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':

username= request.form.get('username')

password= request.form.get('password')

if username==params['admin_user'] AND password==params['password']:

title= request.form.get('title')

content= request.form.get('content')

.....

@app.route('/upload', methods=['GET', 'POST'])

def upload():

app.config['UPLOAD_FOLDER']='D:\\flask_demo\\static'

if request.method=='POST':

f=request.files['file_name']

f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))

return "File has been uploaded successfully"

@app.route('/pagination', methods=['GET', 'POST'])

def pagination():

all_post

last_post=math.floor(len(all_post)/int(no_of_post))

page=int(request.arg.get['page'])

if (not str(page).isnumeric()):

page =1

all_post=all_post[(page-1)*no_of_post: (page-1)*no_of_post+no_of_post]

if page==1:

prev="#"

next="next?"+str(page+1)

elif page==last_post:

prev="next?"+str(page-1)

next="#"

else:

prev="next?"+str(page-1)

next="next?"+str(page+1)

return render_template("post.html", params=params, posts=posts, prev=prev, next=next)

Django Python Command

Verify Python Installation

>python

Check Python Version

>python --version

shortcut command

>python -V

>python3 -V

Check if PIP is Already Installed

>pip help

Installing PIP On Windows Machine

Download PIP get-pip.py

Copy PIP code and save file name is get-pip.py

PIP is a command-line program. When you install PIP, the PIP command is added to your system.

>python  get-pip.py

Check PIP Version

>pip --version

shortcut command

>pip -V

Upgrading PIP for Python on Windows Machine

>python -m pip install --upgrade pip

Downgrade PIP Version

>python -m pip install pip==18.1

Creating virtual environment for window Machine

>python -m virtualenv env

Activate virtual environment for window Machine

>env\scripts\activate

Create Virtual environment for ubuntu/linux machine

>python -m venv env

Activate virtual environment for ubuntu/linux machine

>source env/bin/activate

Deactivate virtual environment

>deactivate

Install django and mysqlclient sh > pip install django > pip install mysqlclient

Install Django

>python -m pip install django

shortcut command

>pip install django

If you wante to install Specific version of django

>pip install django==3.1.7

Check Django Version

>django-admin --version

Install mysqlclient for MYSQL Database

>pip install mysqlclient

if you got installation error in window 

 then download whl files from here

Download :  https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

for window 32 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

for window 64 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl

Creating Django Project

>django-admin startproject demo_project

Creating Django APP

>django-admin startapp demo_app

Note: django-admin is equal to python manage.py command

i.e django-admin = python manage.py

>python manage.py startapp demo_app

Django Migration Command

>python manage.py makemigrations

>python manage.py migrate

Create Super User for Django admin

>python manage.py createsuperuser

Run Server for Django Project

>python manage.py runserver

Exporting data from a Django project

>python manage.py dumpdata > vishavjeet_data.json

If you want the exported file to have a readable JSON,

 then you can use "--indent".

>python manage.py dumpdata --indent=4 > dumped_data.json

Importing data from a Django project

>python manage.py loaddata < vishavjeet_data.json

First Previous 1 2 3 4 Next Last