• python Web框架 Django学习(1)


    有个需求,目前准备用python来实现,所以有了这么个东西。

    在国内貌似Django还是挺适合python Web开发的。所以选择它 -<-.

    具体安装过程就不谈了,记录下创建项目和修改的地方。

    首先是settings.py在当前项目下的文件夹.

    # vim: set fileencoding=utf-8:
    """
    Django settings for web_scan_django project.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/dev/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/dev/ref/settings/
    """
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'px-xyvm8_hj+na$qk!21hq=uynh15ang7@1mee*_om@r)+ig1#'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    TEMPLATE_DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth', # 身份验证系统
        'django.contrib.contenttypes', # 内容类型
        'django.contrib.sessions', # session框架
        'django.contrib.messages', # 消息框架
        'django.contrib.staticfiles', # 静态文件管理框架
    )
    
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    

     数据库配置很重要,所以额外贴。

    # 数据库设置
    DATABASES = {
          'default': {
             'ENGINE': 'django.db.backends.mysql',
             'NAME': 'django_test',
             'USER': 'root',
             'PASSWORD': '',
             'HOST': 'localhost',
         }
    }
    
    # Internationalization
    # https://docs.djangoproject.com/en/dev/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True

    配置完直接运行会报错。。具体两种原因:

    1)数据库没起来。

    2)数据库里没有这个库。

    root@smart:~/web_scan_django# python manage.py runserver 818
    Validating models...
    
    0 errors found
    Unhandled exception in thread started by <function wrapper at 0x34b3d70>
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 170, in wrapper
        fn(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 104, in inner_run
        self.check_migrations()
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 154, in check_migrations
        executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 14, in __init__
        self.loader = MigrationLoader(self.connection)
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 42, in __init__
        self.build_graph()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 139, in build_graph
        self.applied_migrations = recorder.applied_migrations()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 48, in applied_migrations
        self.ensure_schema()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 38, in ensure_schema
        if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 157, in cursor
        cursor = self.make_debug_cursor(self._cursor())
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 129, in _cursor
        self.ensure_connection()
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 124, in ensure_connection
        self.connect()
      File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 93, in __exit__
        six.reraise(dj_exc_type, dj_exc_value, traceback)
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 124, in ensure_connection
        self.connect()
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 112, in connect
        self.connection = self.get_new_connection(conn_params)
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 458, in get_new_connection
        conn = Database.connect(**conn_params)
      File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/__init__.py", line 81, in Connect
        return Connection(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 187, in __init__
        super(Connection, self).__init__(*args, **kwargs2)
    django.db.utils.OperationalError: (1049, "Unknown database 'django_test'")

    第二种错误:

    root@smart:~/web_scan_django# python manage.py syncdb
    Traceback (most recent call last):
      File "manage.py", line 10, in <module>
        execute_from_command_line(sys.argv)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 423, in execute_from_command_line
        utility.execute()
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 415, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 243, in run_from_argv
        self.execute(*args, **options.__dict__)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 290, in execute
        output = self.handle(*args, **options)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 429, in handle
        return self.handle_noargs(**options)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/syncdb.py", line 22, in handle_noargs
        call_command("migrate", **options)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 170, in call_command
        return klass.execute(*args, **defaults)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 290, in execute
        output = self.handle(*args, **options)
      File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 62, in handle
        executor = MigrationExecutor(connection, self.migration_progress_callback)
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 14, in __init__
        self.loader = MigrationLoader(self.connection)
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 42, in __init__
        self.build_graph()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 139, in build_graph
        self.applied_migrations = recorder.applied_migrations()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 48, in applied_migrations
        self.ensure_schema()
      File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 38, in ensure_schema
        if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 157, in cursor
        cursor = self.make_debug_cursor(self._cursor())
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 129, in _cursor
        self.ensure_connection()
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 124, in ensure_connection
        self.connect()
      File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 93, in __exit__
        six.reraise(dj_exc_type, dj_exc_value, traceback)
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 124, in ensure_connection
        self.connect()
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 112, in connect
        self.connection = self.get_new_connection(conn_params)
      File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 458, in get_new_connection
        conn = Database.connect(**conn_params)
      File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/__init__.py", line 81, in Connect
        return Connection(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 187, in __init__
        super(Connection, self).__init__(*args, **kwargs2)
    django.db.utils.OperationalError: (1049, "Unknown database 'django_test'")

    最后把库给建立好,然后再启动脚本,创建库表,即可!

    root@smart:~/web_scan_django# mysql -h localhost -u root -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or g.
    Your MySQL connection id is 41
    Server version: 5.5.30-1.1 (Debian)
    
    Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
    
    mysql> create database django_test;
    Query OK, 1 row affected (0.08 sec)
    
    mysql> exit
    Bye
    root@smart:~/web_scan_django# python manage.py syncdb
    Operations to perform:
      Synchronize unmigrated apps: admin, contenttypes, auth, sessions
      Apply all migrations: (none)
    Synchronizing apps without migrations:
      Creating tables...
        Creating table django_admin_log
        Creating table auth_permission
        Creating table auth_group_permissions
        Creating table auth_group
        Creating table auth_user_groups
        Creating table auth_user_user_permissions
        Creating table auth_user
        Creating table django_content_type
        Creating table django_session
      Installing custom SQL...
      Installing indexes...
    Installed 0 object(s) from 0 fixture(s)
    Running migrations:
      No migrations needed.
    
    You just installed Django's auth system, which means you don't have any superusers defined.
    Would you like to create one now? (yes/no): yes
    Username (leave blank to use 'root'): root 
    Email address: root@163.com
    Password: 
    Password (again): 
    Superuser created successfully.
  • 相关阅读:
    python语法_1基础语法概述
    Pytest用例编写1
    Pytest介绍
    9、Selenium grid2
    虫师Selenium2+Python_8、自动化测试高级应用
    虫师Selenium2+Python_7、unittest单元测试框架
    虫师Selenium2+Python_6、Selenium IDE
    虫师Selenium2+Python_5、自动化测试模型
    虫师Selenium2+Python_4、webdriver API
    虫师Selenium2+Python_3、Python基础
  • 原文地址:https://www.cnblogs.com/xiaoCon/p/3497198.html
Copyright © 2020-2023  润新知