I am not able to add form entries to my database - sqlite

Problem
I am trying to push username and password entries to my database using following code(named as application.py inside my project)
Code
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
application = Flask(__name__)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydtb.db'
db = SQLAlchemy(application)
class Mydtb(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement = True)
user = db.Column(db.String(50), nullable = False)
password = db.Column(db.String(20), nullable = False)
created = db.Column(db.DateTime, default = datetime.utcnow)
def __init__(self, user, password):
user = self.user
password = self.password
#application.route('/', methods=['POST', 'GET'])
def home():
title = 'Registration page'
if request.method == 'POST':
record = Mydtb(request.form['usrname'], request.form['pwd'])
db.session.add(record)
db.session.commit()
return redirect('/')
else:
mydtb = Mydtb.query.order_by(Mydtb.created)
return render_template('index.html', title=title, mydtb = mydtb)
if __name__ == '__main__':
application.run(debug = True)
I've already generated .db file, html form is also working fine but it seems application.py code is unable to push those form entries to database.
You can see the error that I am getting from debug section , I want to fix it without using extra libraries.

Related

How to retrieve user object using PostMan to test my endpoints

Users can create and maintain their profiles rather than enter in
their information each time they order
API Actions:
Retrieve a User Object and its fields by their username
Update the user and any of their fields except for mail
This is my code below:
views.py
"""api views inlcude method: customer list, """
#csrf allows for post without auth
#csrf_exempt
def List_All_Customers(request):
customer = Customer.objects.all()
#returns all the customer from db
if request.method == 'GET':
serializer = CustomerSerializer(customer, many=True)
return JsonResponse(serializer.data, status= 200, safe=False)
#add new customer in the db
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CustomerSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
#csrf_exempt
def Customer_detail(customer):
#check if the customer with the given name is in the database
try:
customer = Customer.objects.filter(name = name)
#if not in database, throw 400 error
except Customer.DoesNotExist:
return HttpResponse(status = 404)
#if customer exists with the given name and is a get method, return that name object
if request.method == 'GET':
serializer = CustomerSerializer(customer)
return JsonResponse(serializer.data)
#delete method will delete the customer with a specific name
elif request.method == 'DELETE':
Customer.objects.filter(name = name).delete()
return HttpResponse(status=204)
#csrf_exempt
def get_current_user(request):
if request.method == 'POST':
customer = request.POST.get('name')
customer = authenticate(user=user)
if customer:
if customer.is_authenticated:
signBool = signatureAuth(username)
if signBool == 'AUTHENTICATED':
login(request, customer, backend=settings.AUTHENTICATION_BACKEND[0])
return JsonResponse(serializer.data)
'''
return JsonResponse({
'user':customer.user,
'name':customer.name,
'email':customer.email,
})
'''
model.py
class Customer(models.Model):
user=models.CharField(max_length=200,null=True)
name=models.CharField(max_length=200,null=True)
email=models.CharField(max_length=200,null=True)
password=models.CharField(max_length=200,null=True)
card_info=models.CharField(max_length=200,null=True)
def __str__(self):
return str(self.Customer)

Discord.py SQLite3 Banned Word System - Issue

So, i tried making a banned word system using sqlite3, but i've ran into a issue and it doesn't error at all nor does it work
My code: ( yes i imported sqlite3 ) & the formatting is correct, its just the code it self
#commands.Cog.listener()
async def on_message(self, member):
db = sqlite3.connect('.//SQL//bannedwords.sqlite')
cursor = db.cursor()
cursor.execute(f'SELECT msg FROM bannedwords WHERE guild_id = {message.guild.id}')
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
result = cursor.fetchone()
await message.author.delete()
embed=discord.Embed(title="Blacklisted Word", description="Test")
await message.send(embed=embed, delete_after=7.0)
#commands.group(invoke_without_commands=True)
async def add(self, ctx):
return
#add.command()
async def word(self, ctx, channel:discord.TextChannel):
if ctx.message.author.guild_permissions.administrator:
db = sqlite3.connect('.//SQL//bannedwords.sqlite')
cursor = db.cursor()
cursor.execute(f'SELECT msg FROM bannedwords WHERE guild_id = {ctx.guild.id}')
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO bannedwords(guild_id, msg) VALUES(?,?)")
val = (ctx.guild.id, msg)
await ctx.send(f"h")
elif result is not None:
sql = ("UPDATE bannedwords SET msg = ? WHERE guild_id = ?")
val = (msg, ctx.guild.id)
await ctx.send(f"added")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
I am aware that i put a text channel, but i don't think thats the only issue - or rather i'm not too sure on what do i replace it with for it to detect messages that are in the msg column
Use message.channel.send instead of message.send.

Flask db.Column(db.Boolean) not updating for email confirmation

i am trying to update a db column but it's not working for some reason, the boolean value is not changing to True. in database it is always False even when i confirm the email try token.
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer(),primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
password = db.Column(db.Integer)
date_added = db.Column(db.DateTime)
confirmed_email = db.Column(db.Boolean, nullable=True, default=False)
def __init__(self,name,email,password,date_added):
self.name = name
self.email = email
self.password = password
self.date_added = date_added
and this is my route for token
#app.route('/confirm_email/<token>')
def confirm_email(token):
try:
email = serializer.loads(token, salt='true', max_age=250)
except SignatureExpired:
return 'The token is expired for'
user = User.query.filter_by(email=email).first()
user.confirmed_email = True
db.session.add(user) #<-- i tried also without this line
db.session.commit()
return redirect(url_for('index'))

Script to create new Folder in Alfresco repository

I want to create a script who allow me to create a new folder in Alfresco repository, but i haven't any idea to how achieve this.
Is there anyone who can tell me how to manage this.
Sorry for not posting any code, because i'm very new to alfresco and i haven't idea how to manage this.
The best way to create a folder (or perform other CRUD functions) remotely, such as from a command line program, is to use CMIS. There are a number of CMIS client implementations depending on what language you'd like to use. These are managed at the Apache Chemistry project.
Here is an example that uses cmislib, a Python CMIS client, to create a folder:
from cmislib.model import CmisClient
from cmislib.browser.binding import BrowserBinding
client = CmisClient('http://localhost:8080/alfresco/api/-default-/cmis/versions/1.1/browser', 'admin', 'admin', binding=BrowserBinding())
repo = client.defaultRepository
folder = repo.getObjectByPath("/User Homes")
createdFolder = folder.createFolder("another test folder")
print "Done, created: %s" % createdFolder.id
Here is an example that uses OpenCMIS, a Java implementation, from Groovy:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-bindings", version="0.13.0")
import org.apache.chemistry.opencmis.commons.*;
import org.apache.chemistry.opencmis.commons.enums.*;
import org.apache.chemistry.opencmis.client.*;
import org.apache.chemistry.opencmis.client.api.*;
import org.apache.chemistry.opencmis.client.runtime.*;
import org.apache.chemistry.opencmis.commons.data.*;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.*;
import org.apache.chemistry.opencmis.commons.exceptions.*;
import java.nio.file.Paths
import groovy.json.JsonOutput
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import java.text.NumberFormat;
def ALF_SERVICE = '/alfresco/s'
def CMIS_SERVICE = '/alfresco/api/-default-/public/cmis/versions/1.1/browser'
final BindingType CMIS_BINDING = BindingType.BROWSER;
// Get options
def url = System.console().readLine('Alfresco server URL [http://localhost:8080]: ')
if (url == null || url == '') url = "http://localhost:8080"
def folderPath = System.console().readLine('Folder path [/User Homes]: ')
if (folderPath == null || folderPath == '') folderPath = "/User Homes"
def folderName = System.console().readLine('Folder name to create: ')
def userName = System.console().readLine('Your username: ')
def password = System.console().readPassword('Your password: ')
println 'WARNING: About to modify folders on ' + url + ' as ' + userName + '.'
def confirm = System.console().readLine('Are you sure (Y/N): ')
if (confirm.toLowerCase() != 'y' && confirm.toLowerCase() != 'yes') {
println "Quitting"
System.exit(0)
}
// Login to Alfresco
def client = new RESTClient(url)
def resp = client.get(path : ALF_SERVICE + '/api/login', query: ['u': userName, 'pw': password.toString(), 'format': 'json'])
assert resp.status == 200
def ticket = resp.data.data.ticket
println "Successfully logged in to Alfresco..."
// Leave the username as an empty string to auth with a ticket
Session session = createCMISSession(url + CMIS_SERVICE, CMIS_BINDING, "", ticket);
Folder folder = findFolder(session, folderPath)
if (folder == null) {
println "ERROR: Could not find: " + folderPath
System.exit(0)
}
println "Found: " + folder.name + " (" + folder.id + ")"
Map<String,String> newFolderProps = new HashMap<String, String>()
newFolderProps.put("cmis:objectTypeId", "cmis:folder");
newFolderProps.put("cmis:name", folderName);
Folder createdFolder = folder.createFolder(newFolderProps)
println "Done, created: " + createdFolder.id
Session createCMISSession(final String cmisEndpointUrl,
final BindingType cmisBinding,
final String cmisUser,
final String cmisPassword) {
SessionFactory sf = SessionFactoryImpl.newInstance();
Session result = null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(SessionParameter.BINDING_TYPE, cmisBinding.value());
parameters.put(SessionParameter.BROWSER_URL, cmisEndpointUrl);
parameters.put(SessionParameter.USER, cmisUser);
parameters.put(SessionParameter.PASSWORD, cmisPassword);
// Note: grabbing the first repository may not work as expected on multi-tenant Alfresco (most notably Cloud)
result = sf.getRepositories(parameters).get(0).createSession();
return (result);
}
Folder findFolder(Session session, String folderPath) {
Folder result = null;
try {
CmisObject folder = session.getObjectByPath(folderPath);
if (folder != null &&
BaseTypeId.CMIS_FOLDER.equals(folder.getBaseTypeId())) {
result = (Folder) folder;
}
} catch (CmisObjectNotFoundException confe) {
// Swallow and move on - we return null in this case
println "ERROR: getObjectByPath threw a CmisObjectNotFoundException"
}
return (result);
}
In the Groovy example, I am logging in and getting a ticket so that I can make both CMIS and non-CMIS calls, although I am not showing any non-CMIS calls in this example.
var nodeNew = parentNode.createFolder("Name of folder");
Above code will create folder using alfresco javascript.parentNode is an object of Node.
Below link have some more details on it.
https://community.alfresco.com/thread/166358-webscript-to-create-folder-space

Flask Bcrypt TypeError: initializer for ctype 'char *' must be a cdata pointer, not NoneType

Encountered this bug. Being an amateur coder I'm really struggling to figure out what I'm doing wrong.
File "C:\Users.virtualenvs\flask\lib\site-packages\bcrypt__init__.py", line 63, in hashpw
retval = _bcrypt.lib.crypt_rn(password, salt, hashed, len(hashed))
TypeError: initializer for ctype 'char *' must be a cdata pointer, not NoneType
Models.py
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password = db.Column(db.String(100))
posts = db.relationship('Post', backref='author', lazy='dynamic',
primaryjoin="User.id==Post.user_id")
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
followed = db.relationship('User',
secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
#reviews = db.relationship('Review', backref='author', lazy='dynamic') This is the review connectino for the user.
#hybrid_property
def password_hash(self):
return self.password
#password_hash.setter
def set_password(self, plaintext):
self.password = bcrypt.generate_password_hash(plaintext)
def is_correct_password(self, plaintext):
return bcrypt.check_password_hash(self.password, plaintext)
Views.py
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(nickname=form.nickname.data).first_or_404()
if user.is_correct_password(form.password.data):
login_user(user)
flash("you've been logged in!, 'success'")
return redirect(url_for('index'))
else:
flash('your email or password doesnt match!', 'error')
return redirect(url_for('login'))
return render_template('login.html',
title='Sign In',
form=form)

Resources