M
M
Mark Rosenthal2014-09-01 19:29:53
JavaScript
Mark Rosenthal, 2014-09-01 19:29:53

Is the registration form correct in python?

Hey!
Actually, I think, if you don’t use MySQL on the site, but do this:

#! /usr/bin/python3
# coding: UTF-8

db = {'user':'userpass','root':'rootpass','admin':'adminpass','moderator':'modepass'} # Это в качестве базы данных
new_user = input("Введите логин: ") #Здесь юзер вводит данные
new_user_pass = input("Введите пароль: ")
db[new_user] = new_user_pass #Добавляем логин:пароль в наш словарь

I think there are a thousand ways to make it easier, but I was told better by a dictionary.
Additional data is also needed here: City, avatar, real name and ... what else do people indicate about themselves?
Well, in general, I even doubt such an implementation, I'm just thinking about the idea.
In jung, everything is done differently.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
E
Eugene, 2016-07-30
@Nc_Soft

You will not believe...
<img src="path/to/image">

K
Konstantin Gromov, 2016-08-01
@Pathgk

This task requires working with binary data, which the jquery ajax wrapper does not support out of the box. Therefore, it is easier to use the native interface:

function fetchBlob(url, callbacks) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'blob';

    if (callbacks) {
        for (var key in callbacks) {
            if (key.indexOf('on') === 0) {
                xhr[key] = callbacks[key];
            }
        }
    }

    xhr.send();
}

fetchBlob('/path/to/image.jpg', {
    onprogress: function (event) {
        console.log(Math.round(event.loaded / event.total * 100) + '%');
    },
    onload: function () {
        $('.container').html('<img src="' + URL.createObjectURL(this.response) + '">');
    }
});

For your version with base64 to work, you need to send the image from the server in this format.

S
s1dney, 2014-09-01
@s1dney

Well, in general, it is, of course, everything is true. But when restarted, the db variable will be in the original state.
So you need to save this business somewhere, for example, write it to a file. The scenario is this: open the file, read the database. Its OK.
When a user is added, you need to add an entry to the database + add an entry to the file. This is no longer OK, because it can cause data inconsistencies in these 2 dictionaries.
And if the program crashes with an error while adding a user? So it is necessary to provide for an urgent dump of the current instance of the dictionary to a file upon exit. This is also not ok.
We could go on like this for a long time, but I'll stop here and just say that the idea is bad. Bearded guys almost 50 years ago came up with cool things for working with data and now they are called "traditional", no need to reinvent the wheel.

A
Andrey Grinevich, 2014-09-02
@Derfirm

In fact, fast sites use traditional databases in one way or another. Both SQL and NoSQL ;)

B
bromzh, 2014-09-04
@bromzh

The easiest way is to use OpenID for authentication. After a successful server response, you receive some user data, but it is not necessary to store them. You can not use the database, just keep the cookie for a while.
Well, if you need to store some additional data - store them in the class field of a certain class.

class User(object):
    clients = set()  # можно использовать и список
                     # можно и словарь, чтобы быстро получать 
                     # конкретного пользователя по какому-то ключу

    def __init__(self, user=None, root=None, admin=None, moderator=None, **kwargs):
        self.user = user
        self.root = root
        self.admin = admin
        self.moderator = moderator
        # Записываем в класс необходимые поля из kwargs
        self.foo = kwargs.pop('foo', 'default_value')

    def auth(self):
        # тут аутентифицируем юзера
        # данные, которые пришли в ответ, можно записать в поля класса
        # после того, как всё записал, делай так:
        self.clients.add(self)  # добавляем подключившегося пользователя
        # Этот массив/сет/словарь будет доступен из любого экземпляра этого класса
        # и из самого класса тоже, например: [print(client) for client in User.clients]

# чтобы хранить данные между перезагрузкой сервера, можно использовать pickle:
import pickle
with open('foo.pickle', 'w') as f:
    pickle.dump(f, User.clients)
# загружать так же:
with open('foo.pickle'. 'r') as f:
    User.clients = pickle.load(f)

Here is a simple example to be clearer:
>>> class A(object):
...     c = list()
...     def __init__(self, **kwargs):
...         self.__dict__.update(**kwargs)
...     def save(self):
...         self.c.append(self)
... 
>>> a = A(a=1, b=2)
>>> a.save()
>>> b = A(a=[3, 4], foo={1, 2})
>>> b.save()
>>> A.c
[<__main__.A object at 0x7fd63603d0b8>, <__main__.A object at 0x7fd63603dc18>]
>>> pickle.dumps(A.c)
b'\x80\x03]q\x00(c__main__\nA\nq\x01)\x81q\x02}q\x03(X\x01\x00\x00\x00bq\x04K\x02X\x01\x00\x00\x00aq\x05K\x01ubh\x01)\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08cbuiltins\nset\nq\t]q\n(K\x01K\x02e\x85q\x0bRq\x0ch\x05]q\r(K\x03K\x04eube.'
>>> A.c = []
>>> A.c = pickle.loads(b'\x80\x03]q\x00(c__main__\nA\nq\x01)\x81q\x02}q\x03(X\x01\x00\x00\x00bq\x04K\x02X\x01\x00\x00\x00aq\x05K\x01ubh\x01)\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08cbuiltins\nset\nq\t]q\n(K\x01K\x02e\x85q\x0bRq\x0ch\x05]q\r(K\x03K\x04eube.')
>>> A.c
[<__main__.A object at 0x7fd63604ca58>, <__main__.A object at 0x7fd63604c908>]
>>> A.c[0].a
1
>>> A.c[1].a
[3, 4]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question