アプリケーションでは、次の目的のために郵便番号を使用しています。

多くのサイトでは、ユーザーは自分の住所を尋ねられると思います。 配信するかどうか、紙のスパム通知を送信するかどうか。 そして、一般的に-これは些細なことです。 私はインデックス、 モスクワ、地域、地区、村、通り、家、アパートを運転しました。 単純化するものがあるように思われます。誰もが彼の住所を覚えているように見えますが、ドライブするのは難しいですか? しかし、悪魔はいつものように詳細にあります。ユーザーはアドレスに封印されており、パッケージは間違った方向に進み、「良い」光線はあなたのフィードバックに入り、一般的には悪化します。



アドレスの最初の部分であるインデックスをよく見てください。 この6桁のセットには、すでに地域、地区、市/村があります。 それらは自動的に置き換えることができます。 これにより、2つの鳥が1つの石で殺されます。

ポイントは小さいです。郵便番号データベースが必要です。



そして彼女は! 最も小さく、電子的で、最も重要なのは、ロシア郵便局の公式インデックスデータベースです。



会う: vinfo.russianpost.ru/database/ops.html



このデータベースは、若い開発者向けのDBF形式で既に奇抜な形式で提供されており、定期的に(月に2回)更新されます。



もちろん、このデータベースはFIASに詳細に到達していませんが、当然のことながら、はるかに単純です(1つのテーブルだけです!)



私たちは...に幸福を留めます。さて、サイトに行きましょう。



そのため、喜んでベースをダウンロードし、使用しているKakTamunasModernSQL(またはNonSQL)にそれを押し込む方法について考えます。



私たちはGoogleで検索し、Yandexで検索し、apt-cacheで検索します。



envek@envek-work:~$ apt-cache search dbf pgdbf - converter of XBase / FoxPro tables to PostgreSQL dbf2mysql - xBase <--> MySQL
      
      





すごい! 私はPostgresを使用し、それに変換します。 ベースもdosovskayaエンコードを使用するため、ヘルプについてiconvを呼び出します。 ちなみに、pgdbfの最新バージョン(> = 0.6.2)自体はシャーマニズムを所有し、iconvを呼び出しますが、Ubuntuリポジトリにはまだ到達していません。



 mv {PIndx08,post_indices}.dbf #  ,     pgdbf -u post_indices.dbf | iconv -f CP866 > post_indices.sql # 
      
      





さて、今それを機能させる必要があります。



私はRuby on Railsを使用していますが、例を挙げて説明します。 レールを理解していない人は、スクロールできます。



データベースからの情報であり、アプリケーションで表されるモデルを作成します

 rails g model PostIndex
      
      





移行では、元のデータベースからテーブル構造を慎重にコピーし、インデックスを主キーにします。

 class CreatePostIndices < ActiveRecord::Migration def change create_table :post_indices, id: false do |t| t.string :index, limit: 6 t.string :ops_name, limit: 60 t.string :ops_type, limit: 50 t.string :ops_subm, limit: 6 t.string :region, limit: 60 t.string :autonom, limit: 60 t.string :area, limit: 60 t.string :city, limit: 60 t.string :city_1, limit: 60 t.date :act_date t.string :index_old, limit: 6 t.index :index_old end reversible do |to| to.up do execute 'ALTER TABLE post_indices ADD PRIMARY KEY (index);' end end end end
      
      





少しカスタマイズ可能なモデル:

 class PostIndex < ActiveRecord::Base self.primary_key = 'index' end
      
      





json形式の郵便番号を提供する簡単なコントローラーを作成します。

 #  : rails generate controller PostIndices class PostIndicesController < ApplicationController def get @index = PostIndex.where(index: params[:index]).first @index = PostIndex.where(index_old: params[:index]).order(:index).first! unless @index respond_to do |format| format.json { render json: @index.to_json(only: [:index, :region, :area, :city]) } end end end
      
      





config / routes.rbに、アプリケーションが目的のインデックスを返すルートを書き込みます。

 get '/post_index/:index(.:format)', controller: :post_indices, action: :get
      
      





そして、最も重要なこと:htmlとjavascript。これらはユーザーにすべての魔法を与えます。



HTMLフォーム:

 <form id='address_form'> <table> <tr> <td><label for='address_postcode'> </label></td> <td> <input class='postcode_field' id='address_postcode' name='address[postcode]'> <p class='description'>   ,  «», «»  «»  .</p> </td> </tr> <tr> <td><label for='address_region'>//</label></td> <td><input class='region_field' id='address_region' name='address[region]'></td> </tr> <tr> <td><label for='address_area'></label></td> <td><input class='area_field' id='address_area' name='address[area]'></td> </tr> <tr> <td><label for='address_city'>/</label></td> <td><input class='city_field' id='address_city' name='address[city]'></td> </tr> </table> </form>
      
      





Javascriptコード(非常に詳細、ユーザー通知、エラーの検出、インデックスの修正)

 jQuery(document).ready(function($){ $('.postcode_field').on('keyup change', function () { //    var postcode_field = $(this); var form = postcode_field.parents("form"); var region_field = $('.region_field', form); var area_field = $('.area_field', form); var city_field = $('.city_field', form); //    region_field.val(''); area_field.val(''); city_field.val(''); //     -     var postcode = this.value; if (postcode.length == 6) { jQuery.ajax({ dataType: "jsonp", url: 'http://postindexapi.ru/'+postcode+'.json?callback=?', beforeSend: function() { //  ,    $("td:last-child p.description.notice, td:last-child p.description.alert", postcode_field.parents("tr")).remove(); $('<p class="description notice loading"></p>').text("…").appendTo($("td:last-child", postcode_field.parents("tr"))) }, success: function(data){ postcode_field.val(data.index); region_field.val(data.region); area_field.val(data.area); city_field.val(data.city); if (data.index != postcode) { var message = "    : "+postcode+",   : "+data.index; $('<p class="description notice"></p>').text(message).appendTo($("td:last-child", postcode_field.parents("tr"))) } }, error: function (jqxhr, status, e) { var message = '       !'+e; if (e == 'Not Found') message = '      '; if (status == 'timeout') message = '     .   .'; $('<p class="description alert"></p>').text(message).appendTo($("td:last-child", postcode_field.parents("tr"))) console.debug(jqxhr, status, e); }, complete: function () { //   $("td:last-child p.description.loading", postcode_field.parents("tr")).remove(); } }); } }); });
      
      





そして、出来上がり、インデックスを入力すると、地域、都市などが自動的に置換されます。 同時に、ボーナスとして、現在のインデックスの古いインデックスを修正できます(多くの場合、人々はすでに絶望的に古いインデックスを持つ親indicesの住所を持っています)。







もう1つ:データベースを常に新鮮に保つには、たとえば2週間ごとにクラウンで実行されるすくいタスクを作成し、すべてを行います( gem 'nokogiri'



require: false



require: false



できrequire: false



) :



 require 'open-uri' require 'fileutils' require 'nokogiri' namespace :post_index do desc 'Update used post indices database to latest' task update: :environment do # Get info about post indices database url_prefix = 'http://info.russianpost.ru/database' doc = Nokogiri::HTML(open("#{url_prefix}/ops.html")) file = doc.at_css('a[name=newdbdata]+table tr:last-child td:nth-child(4) a').attr :href FileUtils.mkdir_p "#{Rails.root}/tmp/post_indices" dir = Pathname.new("#{Rails.root}/tmp/post_indices") filepath = Pathname.new("#{dir}/#{file}") filepath_success = Pathname.new("#{dir}/#{file}.success") if filepath.exist? and filepath_success.exist? puts 'Already up-to-date.' else # Download, unzip, rename and convert post indices file sh "wget #{url_prefix}/#{file} -O #{filepath}" sh "unzip -o #{filepath} -d #{dir}" dbf_filename = filepath.to_s.gsub /\.zip$/, '.DBF' sh "cp -f #{dbf_filename} #{dir}/post_indices.dbf" sh "pgdbf -u #{dir}/post_indices.dbf | iconv -f CP866 > #{dir}/post_indices.sql" # Import in database config = Abitur::Application.config.database_configuration[::Rails.env] dbh, dbu, dbp, db = config['host'], config['username'], config['password'], config['database'] sh "PGPASSWORD=#{dbp} psql -U #{dbu} -w -h #{dbh} #{db} < #{dir}/post_indices.sql" # Clean up FileUtils.rm [dbf_filename, "#{dir}/post_indices.dbf", "#{dir}/post_indices.sql"], force: true FileUtils.touch filepath_success end end end
      
      





まとめ



長所 :実装、使用、および保守が容易で、最新で軽量

短所 :低い詳細(決済のみ)、キャップのすべての都市、ロシアのメール、なぜですか?



そして最も怠forな



さて、そして最後に。 このような些細なことを気に入っていても、この情報をアプリケーションに激しくドラッグしたくない場合は、特別なミニサービスpostindexapi.ruを作成しました。 上記で説明したとおりに、JSONでインデックスに関する情報を提供します。 あなたの健康を使用してください! 説明書が添付されています。



感謝の気持ちを込めて、プルリクエストとバグレポート、およびgithubリポジトリのヒントや提案も受け付けています: github.com/Envek/postindexapi.ru



ご清聴ありがとうございました。



UPD :2018年の時点で、 postindexapi.ruは労働条件でalexkbsをサポートする絶滅したミニサービスがありました。 そのサービスのAPIは記事に記載されているものとは異なるため、別個のJavaScriptコードを使用します



All Articles